文件上传对应的一个Servlet类

来源:互联网 发布:淘宝买东西后店铺消失 编辑:程序博客网 时间:2024/06/07 10:46
import java.io.IOException;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.io.*;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileItemFactory;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class Upload extends HttpServlet {/** *  */private static final long serialVersionUID = 1L;private static  String baseDir;private static  String allowedType;private static  SimpleDateFormat dirFormat;private static  SimpleDateFormat fileFormat;private static  boolean debug = false;/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException { debug = (new Boolean(getInitParameter("debug"))).booleanValue();//根据XML的配置判断是否是debug模式 if(debug) System.out.println("\r\n---- UploaderServlet initialization started ----");  dirFormat = new SimpleDateFormat("yyyyMM"); fileFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");  baseDir = getInitParameter("baseDir"); if(baseDir==null){ baseDir = "/User/"; }  String realBaseDir = getServletContext().getRealPath(baseDir);//得到完整的文件存储路径 if(debug) System.out.println("-----realBaseDir-----"+realBaseDir);  File baseFile = new File(realBaseDir);//创建realBaseDir文件 if(!baseFile.exists())               //如果该文件不存在,创建该文件。 baseFile.mkdirs();  allowedType = getInitParameter("allow_type"); if(debug){      System.out.println(getInitParameter("allow_type"));     System.out.println("\r\n---- UploaderServlet initialization ended ----"); }}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");out.println("<HTML>");out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");out.println("  <BODY>");out.print("    This is ");out.print(this.getClass());out.println(", using the GET method");out.println("  </BODY>");out.println("</HTML>");out.flush();out.close();}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {if(debug)System.out.println("------begin  post method-----");request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");response.setContentType("text/html");response.setHeader("Cache-Control", "no-cache");Date time = new Date();String filePath = baseDir+dirFormat.format(time);//在文件夹下面根据时间创建文件夹保存图片if(debug)System.out.println("-------filepath-----"+filePath);String fileDirPath = getServletContext().getRealPath(filePath);if(debug)System.out.println("-------fileDirPath------"+fileDirPath);    //System.out.println(request.getContextPath());get the name of web applicationFile fileDir = new File(fileDirPath);//创建文件夹if(!fileDir.exists()){fileDir.mkdirs();}PrintWriter out = response.getWriter();//User fileUpload class of file commons to upload filesDiskFileItemFactory dfif = new DiskFileItemFactory();dfif.setSizeThreshold(1024*100);                                      //保存在内存还是硬盘的临界值dfif.setRepository(new File(request.getRealPath("/")+baseDir+"temp"));//创建临时文件夹ServletFileUpload sfu = new ServletFileUpload(dfif);                 //根据DiskFileItemFactory创建ServletFileUpload对象sfu.setSizeMax(1024*1024*4);                                         //一次上传的文件最大值List fileList = null;try{List items = sfu.parseRequest(request);                     //ServletFileUpload解析请求对象Map  fields=new HashMap();Iterator iterators = items.iterator();while(iterators.hasNext()){FileItem fileItem = (FileItem)iterators.next();if(fileItem.isFormField()){                         //如果是普通的文本对象fields.put(fileItem.getFieldName(), fileItem.getString());}else{                                              //文件上传表单域long size = fileItem.getSize();             //得到上传文件的大小 String fileLocalName = fileItem.getName();  //上传文件的名字,原来的名字if("".equals(fileLocalName)||size==0){      //处理没有上传文件的情况out.println("请重新操作,选择上传的文件");out.println("<form><input type='button' value='Click to return ' onClick='window.history.go(-1)'/> </form>");return ;}if(debug)System.out.println("---------file local name------"+fileLocalName);fileLocalName = fileLocalName.replace("\\", "/");//对文件名字解析,注意转义符if(debug)System.out.println("---------file local name------"+fileLocalName);String[]  pathParts = fileLocalName.split("/");String fileName = pathParts[pathParts.length-1];if(debug)System.out.println("----------file name------"+fileName);String ext1=fileLocalName.substring(fileLocalName.lastIndexOf(".")+1);//这一句和下面的ext相同的效果if(debug)   System.out.println("-------ext1-----"+ext1);String ext = fileName.substring(fileName.lastIndexOf(".")+1);if(debug)System.out.println("------ext------"+ext);fileName = fileFormat.format(time)+"."+ext;if(debug)System.out.println("----------file name------"+fileName);File fileToSave = new File(fileDirPath,fileName);//创建文件System.out.println("--------1");String fileUrl = fileDirPath +"/"+ fileName;     //文件路径if(debug)System.out.println("------fileUrl-----"+fileUrl);System.out.println("--------3");if(!extAllowed(allowedType,ext)){                //判断是否是XmL文件中定义的合法类型System.out.println(4);out.println("Type "+ext+" is not allowed to upload");out.println("<form><input type='button' value='Click to return ' onClick='window.history.go(-1)'/> </form>");    return;}System.out.println("--------2");try{fileItem.write(fileToSave);               //将内容写到指定的文件中,这个文件必须是一个已经创建的out.println("file has already been uploaded;");out.println("<a href='index.jsp'>Click to return</a>");}catch(Exception e){e.printStackTrace();}}}}catch(FileUploadException e){                               //处理上传中的异常if(e instanceof SizeLimitExceededException){out.println("the size is too big<p />");out.println("<form><input type='button' value='Click to return ' onClick='index.jsp'/> </form>");return ;}e.printStackTrace();}//out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");//out.println("<HTML>");//out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");//out.println("  <BODY>");//out.print("    This is ");//out.print(this.getClass());//out.println(", using the POST method");//out.println("  </BODY>");//out.println("</HTML>");out.flush();out.close();}/** * Returns information about the servlet, such as  * author, version, and copyright.  * * @return String information about this servlet */public String getServletInfo() {return "This is my default servlet created by Eclipse";}public boolean extAllowed(String fileTypes,String str ){     //判断文件类型是否是合法类型的方法String[] allowList = fileTypes.split(",");boolean isexist = false;for(String al:allowList){if(al.equals(str))isexist = true;}return isexist;}}

原创粉丝点击