文件上传过滤类
package com.mvc.interceptor; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.output.DeferredFileOutputStream; import com.mvc.filter.MVCHttpParams; public class UploadInterceptor extends MVCInterceptorAdapter{ @Override public String invoke(MVCHttpParams params) { HttpServletRequest request=params.getRequest(); String contexttype=request.getContentType(); if(!contexttype.equals("application/x-www-form-urlencoded")){ HttpServletResponse response=params.getResponse(); HttpSession session=request.getSession(); response.setCharacterEncoding("UTF-8"); DiskFileItemFactory diskfactory=new DiskFileItemFactory(); diskfactory.setSizeThreshold(4096); File f=new File(request.getSession().getServletContext().getRealPath("/")+"temp"); if(!f.exists()){ f.mkdir(); } diskfactory.setRepository(f); ServletFileUpload sfu=new ServletFileUpload(); sfu.setFileItemFactory(diskfactory); sfu.setFileSizeMax(3*1024*1024); try { List<FileItem> filelist=sfu.parseRequest(request); for(FileItem item:filelist){ if(item.isFormField()){ String name=item.getFieldName(); request.setAttribute(name, item.getString()); if(null==session.getAttribute("UPLOADREQUEST")){ session.setAttribute("UPLOADREQUEST", "true"); } continue; }else{ session.setAttribute("FILEITEM", item); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } @Override public String doAfter(MVCHttpParams params) { HttpSession session=params.getRequest().getSession(); if(session.getAttribute("FILEITEM")!=null){ FileItem item=(FileItem)session.getAttribute("FILEITEM"); DeferredFileOutputStream dfos=null; try { dfos = (DeferredFileOutputStream)item.getOutputStream(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } File file=dfos.getFile(); file.delete(); session.removeAttribute("FILEITEM"); session.removeAttribute("UPLOADREQUEST"); } return null; } }
相关推荐
Kafka 2020-09-18
Wepe0 2020-10-30
杜倩 2020-10-29
windle 2020-10-29
minerd 2020-10-28
mengzuchao 2020-10-22
Junzizhiai 2020-10-10
bxqybxqy 2020-09-30
风之沙城 2020-09-24
kingszelda 2020-09-22
大唐帝国前营 2020-08-18
yixu0 2020-08-17
TangCuYu 2020-08-15
xiaoboliu00 2020-08-15
songshijiazuaa 2020-08-15
xclxcl 2020-08-03
zmzmmf 2020-08-03
newfarhui 2020-08-03
likesyour 2020-08-01