在项目中采用一個Ajax框架Ajax-Upload上传文件,想起曾经使用的FileUpload ,Cos,JspSmartUpload等上传框架加以整理.
Apache Commons FileUpload,可以在 http://jakarta.apache.org/commons/fileupload 找到。目前该项目的最新版本是 1.1.1,网上有大量的范例程序,不过后来用的时候发现大部分方法在新版本中都不推荐使用了,于是好好读了一回 API 和官方范例。
package com.vnvtrip;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
/**
*
* @author longgangbai
*
*/
public class FileUploadServlet extends HttpServlet {
private static String DEFAULT_COS_UPLOAD_DIR = "C://upload";
private static String DEFAULT_FILE_ENCODING_CHARSET = "UTF-8";
/**
* Constructor of the object.
*/
public FileUploadServlet() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
/**
* 使用上传文件
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setCharacterEncoding(DEFAULT_FILE_ENCODING_CHARSET);
request.setCharacterEncoding(DEFAULT_FILE_ENCODING_CHARSET);
// 从 HTTP servlet 获取 fileupload 组件需要的内容
RequestContext requestContext = new ServletRequestContext(request);
// 判断是否包含 multipart 内容
if (ServletFileUpload.isMultipartContent(requestContext)) {
// 创建基于磁盘的文件工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置直接存储文件的极限大小,一旦超过则写入临时文件以节约内存。默认为 1024 字节
factory.setSizeThreshold(1024 * 1024);
// 创建上传处理器,可以处理从单个 HTML 上传的多个上传文件。
ServletFileUpload upload = new ServletFileUpload(factory);
// 最大允许上传的文件大小
upload.setSizeMax(1024 * 1024);
// 处理上传
List items = null;
try {
items = upload.parseRequest(requestContext);
// 由于提交了表单字段信息,需要进行循环区分。
for (int i = 0; i < items.size(); i++) {
FileItem fi = (FileItem) items.get(i);
// 如果不是表单内容,取出 multipart。
if (!fi.isFormField()) {
// 上传文件路径和文件、扩展名。
String sourcePath = fi.getName();
System.out.println("sourcepath" + sourcePath);
// 获取真实文件名
String fileName = sourcePath.substring(sourcePath
.lastIndexOf(File.separator) + 1);
out.println("fileName =" + fileName);
// 创建一个待写文件
File uploadedFile = new File(DEFAULT_COS_UPLOAD_DIR
+ File.separator + fileName);
// 写入
fi.write(uploadedFile);
out.println(fileName + " 上传成功。 ");
}
}
} catch (Exception e) {
out.println(" 上传失败,请检查上传文件大小是否超过1兆,并保证在上传时该文件没有被其他程序占用。 ");
out.println(" <br>原因: " + e.toString());
e.printStackTrace();
}
}
out.flush();
out.close();
}
/**
* Initialization of the servlet.
*
* @throws ServletException
*/
public void init() throws ServletException {
}
}
Web配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>fileUpload</servlet-name>
<servlet-class>com.vnvtrip.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUpload</servlet-name>
<url-pattern>/fileUpload</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
htm页面中:
注意上传文件必须的发送的Post請求同时設置:enctype="multipart/form-data
<form action="./fileUpload" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="上传文件" />
</form>