记得以前写过用commons-fileupload实现的文件上传,可现在又差不多忘了,
于是乎今天在网上找了写资料拼拼凑凑又重新写过了一遍,在此做个备忘!
于是乎今天在网上找了写资料拼拼凑凑又重新写过了一遍,在此做个备忘!
public class FileUpload extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
final long MAX_SIZE= 10 * 1024 * 1024;
String fileFolder = this.getServletContext().getRealPath("/userFiles");
//判断该请求是否是文件上传的请求
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
//设置上传文件时用于临时存放文件的内存大小
factory.setSizeThreshold(10 * 1024);
//设置存放临时文件的目录
factory.setRepository(new File(fileFolder+"/temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
//设置最大上传尺寸
upload.setFileSizeMax(MAX_SIZE);
try {
List<FileItem> filelist = upload.parseRequest(request);
for(Iterator<FileItem> it = filelist.iterator(); it.hasNext() ; ){
FileItem item = it.next();
//判断是form表单域还是上传文件file域
if(item.isFormField()){
//处理form表单域
String name = item.getFieldName();
String value = item.getString();
}else{
//处理fileUpload
//得到表单域的名称
String fieldName = item.getFieldName();
//取得文件类型
String contentType = item.getContentType();
//文件的全路径
String fileName = item.getName();
//得到去除路径的文件名
int index = fileName.lastIndexOf("\\");
fileName = fileName.substring(index+1);
//构建一个文件
File uploadFile = new File(fileFolder ,fileName);
//保存文件
item.write(uploadFile);
out.println("文件上传成功");
}
}
} catch (FileUploadException e) {
if(e instanceof FileSizeLimitExceededException ){
out.println("文件太大,允许上传的最大大小为10MB");
}
} catch (Exception e) {
out.println(e);
}
}
}
}