---
title: "使用apache.commons.fileupload组件来进行文件上传"
author: "zhou_wu"
date: "2011-01-27T11:00:50Z"
tags: []
categories: ["编程语言"]
slug: "apache-commons-fileupload"
draft: false
lastmod: "2011-01-27T11:00:50Z"
id: 898053
url: "https://leesmart.iteye.com/blog/898053"
---

1. 从www.apache.org的common项目下搞到commons-fileupload.jar 和commons-io.jar，导入项目。

2. jsp页面中，form的属性设置要求为：
<form action="uploadServlet" method="post" enctype="multipart/form-data">
其中，post和multipart/form-data要求必须指定。

3. 创建处理请求的Servlet：

```java

<span style="font-size: medium;">DiskFileItemFactory factory = new DiskFileItemFactory();
		// 获得项目根路径
		String path = request.getRealPath("/");	
		// 设置缓存路径
		factory.setRepository(new File(path));
		// 设置文件缓存到硬盘的大小临界值
		factory.setSizeThreshold(1024 * 1024);

		ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
		try {
			// 指定解析request
			List<FileItem> list = (List<FileItem>)
					servletFileUpload.parseRequest(request);
			for (FileItem item : list)
			{
				// 非文件的表单字段
				if (item.isFormField() == true){
					String filedName = item.getFieldName(); // 获得字段名
					String value = item.getString("UTF-8"); // 获得字段值
					System.out.println("fieldName=" + filedName);
					System.out.println("value=" + value);
					
				}else{ //文件表单字段
					String fieldName = item.getFieldName(); // 获得字段名
					String value = item.getName();			// 获得文件名
					System.out.println("fieldName=" + fieldName);
					System.out.println("file path=" + value);
					// 处理浏览器兼容问题处理
					int index = value.lastIndexOf("\\");
					String fileName = value.substring(index + 1);
					
					item.write(new File(path, fileName));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}</span>

```