最近一直看java web如何实现sverlet接收post一次上传的多文件数据。目前找到亲测靠谱的实现方法,已经在项目中跑过可用。
需要用到的jar包:
commons-fileupload-1.3.2.jar(http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi)
commons-io-2.5.jar(http://commons.apache.org/io/download_io.cgi)
代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");//防止中文名乱码
int sizeThreshold=1024*6; //缓存区大小
String basePath = this.getServletContext().getRealPath("/upload/");
System.out.println(basePath);
File repository = new File(basePath); //缓存区目录
long sizeMax = 1024 * 1024 * 2;//设置文件的大小为2M
final String allowExtNames = "jpg,gif,bmp,rar,rar,txt,docx,png";
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 extName=filePath.substring(filePath.lastIndexOf(".")+1);
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();
}
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
out.println("this is Post method");
out.flush();
out.close();
}
项目结构:
服务器一次post上传存储结果: