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上傳存儲結果: