Commons FileUpload

Apache 官网使用指南:http://commons.apache.org/fileupload/using.html

Apache Common fileUpload API 详解:http://www.blogjava.net/gembin/archive/2008/05/08/199240.html


JSP页面:

<form id="form1" name="form1" action="formProcess" method="post" enctype="multipart/form-data">
	File Name: <input type="text" name="name" value="<%=request.getAttribute("line")%>" /> <br />
        File: <input type="file" name="myFile" /> <br />
        <input type="submit" value="Process" />
</form>



Servlet 处理文件上传:

public class FormProcess extends HttpServlet {

	String uploadPath = "D:\\test";

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		String line = null;
		String fileName = null;
		File fullFile = null;

		try {
			// Create a factory for disk-based file items
			DiskFileItemFactory factory = new DiskFileItemFactory();

			// Set factory constraints
			// Apache文件上传组件在解析和处理上传数据中的每个字段内容时,需要临时保存解析出的数据。因为Java虚拟机默认可以使用的内存空间是有
			// 限的(笔者测试不大于100M),超出限制时将会发生“java.lang.OutOfMemoryError”错误
			factory.setSizeThreshold(4096); // your max memory
											// size.设置最多只允许在内存中存储的数据,单位:字节

			// 设置setSizeThreshold方法中提到的临时文件的存放目录,这里要求使用绝对路径
			// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
			// factory.setRepository(new File(uploadPath));

			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);

			// Set overall request size constraint.设置允许用户上传文件大小,单位:字节
			upload.setSizeMax(8194304);

			// Parse the request
			List /* FileItem */items = null;
			items = upload.parseRequest(request);

			// Process the uploaded items
			Iterator iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();

				if (item.isFormField()) {
					/* processFormField(item); */
					// Process a regular form field
					String name = item.getFieldName();
					line = item.getString("UTF-8");
					System.out.println(name + ": " + line);

				} else {
					/* processUploadedFile(item); */
					String fieldName = item.getFieldName();
					fileName = item.getName();
					fullFile = new File(fileName);
					File uploadedFile = new File(uploadPath, fullFile.getName());
					System.out.println(uploadedFile.getAbsolutePath());
					item.write(uploadedFile);
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		request.setAttribute("line", line);
		request.setAttribute("fileName", fullFile.getCanonicalPath());
		this.getServletConfig().getServletContext()
				.getRequestDispatcher("/index.jsp").forward(request, response);
	}

	@Override
	public void init() throws ServletException {
		File uploadDir = new File(uploadPath);
		if (!uploadDir.exists()) {
			uploadDir.mkdirs();
		}
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值