common-fileupload 上传单个或者多个文件 示例

时间:2022-09-30 22:42:30

rui888 推荐的,发现挺不错,留着以后可以用


原文地址:http://www.cnblogs.com/dycg/archive/2010/04/21/1717502.html


该组件对中文支持良好,支持单文件与多文件的同时上传

主要类介绍

  DiskFIleItemFactory类 ,该类创建FileItem对象的工厂类,开发人员可以在这个工厂类上配置上传过程中的

内存缓冲区大小和存放临时文件的目录,其中的repository属性主要指定上传文件保存的目录,sizeThreshold属性

则设置在内存中缓冲区大小

  ServletFileUpload类 该类首先负责处理上传的文件的文件数据,最终完成文件上传的功能。在下面代码中,注意该

类使用时会抛出的一些异常。

  FileItem类,该类包装上传表单中的各个请求属性,可以通过其中的isFormField属性访问方法识别某个FileItem类

对象实际代表的是普通表单成员域还是file类型的成员域

具体使用:

JSP页面: 注意form中标红色的部分,该方法以二进制流的方式来处理表单数据,并且把文件域指定的文件的内容也封装进了请求参数里


<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'filesUpload.jsp' starting page</title>

</head>

<body>
<form action="<%=basePath%>servlet/FileUploadServlet"
        enctype="multipart/form-data" method="post">
<input type="file" name="file1"><br>
<input type="file" name="file2"><br>
<input type="file" name="file3"><br>
<input type="submit">
</form>
</body>
</html>

Servlet代码

package experiment4;

import java.io.File;
import java.io.IOException;
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.FileUploadException;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUploadServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");//防止中文名乱码
int sizeThreshold=1024*6; //缓存区大小
String basePath = this.getServletContext().getRealPath("/upload/");
File repository = new File(basePath); //缓存区目录
long sizeMax = 1024 * 1024 * 2;//设置文件的大小为2M
final String allowExtNames = "jpg,gif,bmp,rar,rar,txt,docx";
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
diskFileItemFactory.setRepository(repository);
diskFileItemFactory.setSizeThreshold(sizeThreshold);
ServletFileUpload servletFileUpload=new ServletFileUpload(diskFileItemFactory);
servletFileUpload.setSizeMax(sizeMax);

List<FileItem> fileItems = null;
try{
fileItems = servletFileUpload.parseRequest(request);

for(FileItem fileItem:fileItems){
long size=0;
String filePath = fileItem.getName();
System.out.println(filePath);
if(filePath==null || filePath.trim().length()==0)
continue;
String fileName=filePath.substring(filePath.lastIndexOf(File.separator)+1);
// String fileName=String.valueOf(System.currentTimeMillis());
String extName=filePath.substring(filePath.lastIndexOf(".")+1);
// fileName+="."+extName;
if(allowExtNames.indexOf(extName)!=-1)
{
try {
fileItem.write(new File(basePath+File.separator+fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
else{
throw new FileUploadException("file type is not allowed");
}
}
}catch(FileSizeLimitExceededException e){
System.out.println("file size is not allowed");
}catch(FileUploadException e1){
e1.printStackTrace();
}


}

}