利用commons-fileupload上传文件

前端JSp页面:

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title></title>
 
	
  </head>
  
  <body>
  
  <form name="uploadform" method="post" action="OnlineExam.do" ENCTYPE="multipart/form-data">
 	<table>
 	<tr>
 			<td>请选择要导入的试卷类型:  </td>
 			<td>
 			<select name="type">
 				<option value="0">请选择导入的试卷类型</option>
 				<option value="1">入门考试</option>
 				<option value="2">职称考试</option>
 				<option value="3">资格考试</option>
 				
 			</select>
 			</td>
 			
 	</tr>
 		<tr>
 			<td>请选择要导入的试卷:</td>
 			<td><input type="file" name="examFile"/><input type="submit" /></td>
 		</tr>
 	</table>
  </form>
</body>
</html>

 后端的JAVA代码:

 

package com.land.aminer.presentation.action;

public class OnlineExamAction extends PubAction {
	private static OnlineExamBiz onlineExamBiz = OnlineExamBiz.getInstance();

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession();
		OASession oaSession = (OASession) session.getAttribute("oaSession");
		String action=request.getParameter("action");
		
		RequestContext requestContext = new ServletRequestContext(request);
		String type="";
//		 f=new FileUpload();
//		f.setHeaderEncoding("UTF-8");
		// 判断表单是否是Multipart类型的。这里可以直接对request进行判断,不过已经以前的用法了
		if (FileUpload.isMultipartContent(requestContext)) {
			
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 设置文件的缓存路径
			factory.setRepository(Repository.getTempDir());
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("utf-8");//中文文件名乱码在这里处理
			// 设置上传文件大小的上限,-1表示无上限
			upload.setSizeMax(-1);
			List items = new ArrayList();
			try {
				// 上传文件,并解析出所有的表单字段,包括普通字段和文件字段
				items = upload.parseRequest(request);
			} catch (FileUploadException e1) {
				e1.printStackTrace();
			}
			// 下面对每个字段进行处理,分普通字段和文件字段
			Iterator it = items.iterator();
			ExamPaper ep=new ExamPaper();
			String fileName="";
			while (it.hasNext()) {
				FileItem fileItem = (FileItem) it.next();
				// 如果是普通字段
				if (fileItem.isFormField()) {
					if ("type".equalsIgnoreCase(fileItem.getFieldName())) {
						ep.setType(Integer.valueOf(fileItem.getString()));
					}
				}else{

//在这里,IE会提供包括路径在内的文件名,我要移除这个路径,可以用FileItemUtils来处理

if (fileItem.getName()!= null)
 {
	fileName = FilenameUtils.getName(fileItem.getName());
 }

					File savedFile = new File(Repository.getExamPaperDir(), fileName );
					fileItem.write(savedFile);
				}
			}
		}

		return mapping.findForward("edit");
	}


}

你可能感兴趣的:(html,jsp,IE,F#)