Java文件上传组件 common-fileUpload 使用教程

fmms 12年前

最近项目中,在发布商品的时候要用到商品图片上传功能(网站前台和后台都要用到),所以单独抽出一个项目来供其他的项目进行调用 ,对外透露的接口的为两个servlet供外部上传和删除图片,利用到连个jarcommons-fileupload-1.2.1.jar,commons-io-1.4.jar

项目结构如下:

项目结构图

其中com.file.helper主要提供读相关配置文件的帮助类

com.file.servlet 是对外提供调用上传和删除的图片的servlet

com.file.upload 是主要提供用于上传和删除图片的接口

1、FileConst类主要是用读取文件存储路径和设置文件缓存目录 允许上传图片的最大值

package com.file.helper;    import java.io.IOException;  import java.util.Properties;    public class FileConst {     private static Properties properties= new Properties();   static{    try {     properties.load(ReadUploadFileType.class.getClassLoader().getResourceAsStream("uploadConst.properties"));    } catch (IOException e) {     e.printStackTrace();    }   }      public static String getValue(String key){    String value = (String)properties.get(key);    return value.trim();   }  }
2、ReadUploadFileType读取允许上传图片的类型和判断上传的文件是否符合约束的文件类型

package com.file.helper;    import java.io.File;  import java.io.IOException;  import java.util.ArrayList;  import java.util.List;  import java.util.Properties;    import javax.activation.MimetypesFileTypeMap;        /**   * 读取配置文件   * @author Owner   *   */  public class ReadUploadFileType {        private static Properties properties= new Properties();   static{    try {     properties.load(ReadUploadFileType.class.getClassLoader().getResourceAsStream("allow_upload_file_type.properties"));    } catch (IOException e) {     e.printStackTrace();    }       }   /**    * 判断该文件是否为上传的文件类型    * @param uploadfile    * @return    */   public static Boolean readUploadFileType(File uploadfile){    if(uploadfile!=null&&uploadfile.length()>0){     String ext = uploadfile.getName().substring(uploadfile.getName().lastIndexOf(".")+1).toLowerCase();     List<String> allowfiletype = new ArrayList<String>();     for(Object key : properties.keySet()){      String value = (String)properties.get(key);      String[] values = value.split(",");      for(String v:values){       allowfiletype.add(v.trim());      }     }     // "Mime Type of gumby.gif is image/gif"      return allowfiletype.contains( new MimetypesFileTypeMap().getContentType(uploadfile).toLowerCase())&&properties.keySet().contains(ext);    }    return true;   }        }
3、FileUpload主要上传和删除图片的功能

package com.file.upload;    import java.io.File;  import java.util.Iterator;  import java.util.List;    import javax.servlet.http.HttpServletRequest;    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 com.file.helper.FileConst;  import com.file.helper.ReadUploadFileType;    public class FileUpload {    private static String uploadPath = null;// 上传文件的目录    private static String tempPath = null; // 临时文件目录    private static File uploadFile = null;    private static File tempPathFile = null;    private static int sizeThreshold = 1024;    private static int sizeMax = 4194304;    //初始化    static{       sizeMax  = Integer.parseInt(FileConst.getValue("sizeMax"));       sizeThreshold = Integer.parseInt(FileConst.getValue("sizeThreshold"));       uploadPath = FileConst.getValue("uploadPath");       uploadFile = new File(uploadPath);          if (!uploadFile.exists()) {              uploadFile.mkdirs();          }          tempPath = FileConst.getValue("tempPath");          tempPathFile = new File(tempPath);          if (!tempPathFile.exists()) {              tempPathFile.mkdirs();          }    }   /**    * 上传文件     * @param request    * @return true 上传成功 false上传失败    */   @SuppressWarnings("unchecked")   public static boolean upload(HttpServletRequest request){    boolean flag = true;    //检查输入请求是否为multipart表单数据。    boolean isMultipart = ServletFileUpload.isMultipartContent(request);    //若果是的话    if(isMultipart){     /**为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。**/     try {      DiskFileItemFactory factory = new DiskFileItemFactory();      factory.setSizeThreshold(sizeThreshold); // 设置缓冲区大小,这里是4kb      factory.setRepository(tempPathFile);// 设置缓冲区目录      ServletFileUpload upload = new ServletFileUpload(factory);      upload.setHeaderEncoding("UTF-8");//解决文件乱码问题      upload.setSizeMax(sizeMax);// 设置最大文件尺寸      List<FileItem> items = upload.parseRequest(request);      // 检查是否符合上传的类型      if(!checkFileType(items)) return false;      Iterator<FileItem> itr = items.iterator();//所有的表单项      //保存文件      while (itr.hasNext()){        FileItem item = (FileItem) itr.next();//循环获得每个表单项        if (!item.isFormField()){//如果是文件类型          String name = item.getName();//获得文件名 包括路径啊          if(name!=null){           File fullFile=new File(item.getName());           File savedFile=new File(uploadPath,fullFile.getName());           item.write(savedFile);          }        }      }     } catch (FileUploadException e) {      flag = false;      e.printStackTrace();     }catch (Exception e) {      flag = false;      e.printStackTrace();     }    }else{     flag = false;     System.out.println("the enctype must be multipart/form-data");    }    return flag;   }      /**    * 删除一组文件    * @param filePath 文件路径数组    */   public static void deleteFile(String [] filePath){    if(filePath!=null && filePath.length>0){     for(String path:filePath){      String realPath = uploadPath+path;      File delfile = new File(realPath);      if(delfile.exists()){       delfile.delete();      }     }         }   }      /**    * 删除单个文件    * @param filePath 单个文件路径    */   public static void deleteFile(String filePath){    if(filePath!=null && !"".equals(filePath)){     String [] path = new String []{filePath};     deleteFile(path);    }   }      /**    * 判断上传文件类型    * @param items    * @return    */   private static Boolean checkFileType(List<FileItem> items){    Iterator<FileItem> itr = items.iterator();//所有的表单项    while (itr.hasNext()){      FileItem item = (FileItem) itr.next();//循环获得每个表单项      if (!item.isFormField()){//如果是文件类型        String name = item.getName();//获得文件名 包括路径啊        if(name!=null){         File fullFile=new File(item.getName());         boolean isType = ReadUploadFileType.readUploadFileType(fullFile);         if(!isType) return false;         break;        }      }    }        return true;   }  }

4、FileUploadServlet上传文件servlet 供外部调用

package com.file.servlet;    import java.io.IOException;    import javax.servlet.ServletException;  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;    import com.file.upload.FileUpload;      @SuppressWarnings("serial")  public class FileUploadServlet extends HttpServlet {      public void doGet(HttpServletRequest request, HttpServletResponse response)     throws ServletException, IOException {    this.doPost(request, response);   }        public void doPost(HttpServletRequest request, HttpServletResponse response)     throws ServletException, IOException {    FileUpload.upload(request);   }    }

5、DeleteFileServlet删除图片供外部调用

package com.file.servlet;    import java.io.IOException;    import javax.servlet.ServletException;  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;    import com.file.upload.FileUpload;    @SuppressWarnings("serial")  public class DeleteFileServlet extends HttpServlet {   public void doGet(HttpServletRequest request, HttpServletResponse response)     throws ServletException, IOException {    this.doPost(request, response);   }     public void doPost(HttpServletRequest request, HttpServletResponse response)     throws ServletException, IOException {    String [] file = request.getParameterValues("fileName");    FileUpload.deleteFile(file);   }    }

6、allow_upload_file_type.properties

gif=image/gif
jpg=mage/jpg,image/jpeg,image/pjpeg
png=image/png,image/x-pngimage/x-png,image/x-png
bmp=image/bmp

7、uploadConst.properties

sizeThreshold=4096
tempPath=c\:\\temp\\buffer\\
sizeMax=4194304
uploadPath=c\:\\upload\\
8外部调用

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  <%  String path = request.getContextPath();  String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  %>    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  <html>    <head>      <base href="<%=basePath%>">            <title>My JSP 'index.jsp' starting page</title>   <meta http-equiv="pragma" content="no-cache">   <meta http-equiv="cache-control" content="no-cache">   <meta http-equiv="expires" content="0">       <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">   <meta http-equiv="description" content="This is my page">   <!--   <link rel="stylesheet" type="text/css" href="styles.css">   -->    </head>        <body>       <form name="myform" action="http://xxx.com/FileUploadServlet" method="post" enctype="multipart/form-data">         File:         <input type="file" name="myfile"><br>         <br>         <input type="submit" name="submit" value="Commit">      </form>    </body>  </html>

转自:http://blog.csdn.net/ajun_studio/article/details/6639306