自定义,文件上传(common-fileupload)
支持jar:
commons-fileupload-1.3.jar、
commons-io-2.4.jar
/** * @title: FileDm.java * @develop: YanXiaojia R&D * @description: 文件上传实体。 * @author: YanXiaojia * @version: 1.00 */public class FileDm {/** * 文件名称 */private String fileName ;/** * 文件类型 */private String fileType ;/** * 允许上传的文件类型 */private String[] fileTypes ;/** * 文件上传保存路径 */private String filePath ;/** * <p>是否验证isMultiPart</p> * 默认不使用, 即 isMultiPart = false. */private Boolean isMultiPart = false;/** * <p>是否使用虚拟目录</p> * 默认不使用, 即 isVirdir = false. */private Boolean isVirdir = false ;/** * <p>缓冲区大小</p> * 默认1M, 即(1024 * 1024 * 1). */private Integer sizeThreshold = (1024 * 1024 * 1);/** * <p>缓冲区目录</p> */private File repository ;/** * <p>是否限制上传文件大小</p> * 默认不限制, 即isLimitSize = false. */private Boolean isLimitSize = false;/** * <p>上传文件最大限制</p> * 默认10M, 即(1024 * 1024 * 10) */private Integer sizeMax = (1024 * 1024 * 10);/** * <p>文件编码</p> * 默认UTF-8,即encoding = "UTF-8". */private String encoding = "UTF-8";/** * 处理文件后缀。 * @param fileName */public void handleFileType(String fileName){this.setFileType(fileName.substring(fileName.lastIndexOf(".") + 1));}/** * 是否被限制上传的文件类型 * @param fileType * @return true:否false:是 */public Boolean isAllowFileType(String fileType){for (int i = 0; i < this.getFileTypes().length; i++) {if(this.getFileTypes()[i].equals(fileType)){return true;}}return false;}/** * 文件全名称(包含文件类型) * @return 文件全名称 */public String getFileNameAll() {return this.getFileName() + "." + this.getFileType();}public String getFileName() {return fileName;}public void setFileName(String fileName) {this.fileName = fileName;}public String getFileType() {return fileType;}public void setFileType(String fileType) {this.fileType = fileType;}public String[] getFileTypes() {return fileTypes;}public void setFileTypes(String[] fileTypes) {this.fileTypes = fileTypes;}public String getFilePath() {return filePath;}public void setFilePath(String filePath) {this.filePath = filePath;}public Boolean getIsMultiPart() {return isMultiPart;}public void setIsMultiPart(Boolean isMultiPart) {this.isMultiPart = isMultiPart;}public Boolean getIsVirdir(){return isVirdir;}public void setIsVirdir(Boolean isVirdir){this.isVirdir = isVirdir;}public Integer getSizeThreshold() {if (!this.getIsVirdir()) {throw new IllegalStateException("isVirdir not set to true, sizeThreshold not operate.");}return sizeThreshold;}public void setSizeThreshold(Integer sizeThreshold) {this.sizeThreshold = sizeThreshold;}public File getRepository() {if (!this.getIsVirdir()) {throw new IllegalStateException("isVirdir not set to true, repository not operate.");}return repository;}public void setRepository(File repository) {this.repository = repository;}public Boolean getIsLimitSize() {return isLimitSize;}public void setIsLimitSize(Boolean isLimitSize) {this.isLimitSize = isLimitSize;}public Integer getSizeMax() {if (!this.getIsLimitSize()) {throw new IllegalStateException("isLimitSize not set to true, sizeMax not operate.");}return sizeMax;}public void setSizeMax(Integer sizeMax) {this.sizeMax = sizeMax;}public String getEncoding() {return encoding;}public void setEncoding(String encoding) {this.encoding = encoding;}}
/** * @title: FileUpload.java * @develop: YanXiaojia R&D * @description: 文件上传工具。 * @author: YanXiaojia * @version: 1.00 */public class FileUpload {/** * 文件上传。 * @param request * @throws Exception */public static FileDm fileUpload(HttpServletRequest request, FileDm fm) throws Exception {// 创建基于磁盘文件项目的工厂DiskFileItemFactory factory = new DiskFileItemFactory();// 缓冲区目录factory.setRepository(fm.getRepository());// 缓冲区大小factory.setSizeThreshold(fm.getSizeThreshold());// 创建一个新文件上传ServletFileUpload upload = new ServletFileUpload(factory);// 设置文件编码upload.setHeaderEncoding(fm.getEncoding());// 设置文件上传大小upload.setSizeMax(fm.getSizeMax());// 检查输入请求是否为multiPart表单数据if (fm.getIsMultiPart()) {boolean isMultiPart = ServletFileUpload.isMultipartContent(request);if (isMultiPart == false) {throw new IllegalStateException("The enctype must be multipart/form-data.");}}// 解析请求List<FileItem> items = upload.parseRequest(request);// 上传项目过程Iterator<FileItem> iter = items.iterator();Boolean flag = true;while (iter.hasNext()) {FileItem item = iter.next();// 处理文件类型fm.handleFileType(item.getName());flag = fm.isAllowFileType(fm.getFileType());if (!flag) {throw new IllegalStateException("Upload file type is restricted.");}// 处理上传File field = new File(fm.getFileNameAll());String filePath = getFilePath(fm.getFilePath(),field.getName());fm.setFilePath(filePath);File file = new File(filePath);item.write(file);}return fm;}public static String getFilePath(String dir, String fileName) {String fileSeparator = System.getProperty("file.separator");if (!dir.endsWith(fileSeparator)) {dir += fileSeparator;}File file = new File(dir);if (!file.isDirectory()) { // 如果文件夹不存在就新建file.mkdirs();}return dir + fileName;}}
/** * Servlet事例 * Servlet implementation class Upload */public class Upload extends HttpServlet {private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {FileUpload fileUpload = new FileUpload();fileUpload.setFileName(UUID.randomUUID().toString());// 允许上传的文件类型。fileUpload.setFileTypes(new String[]{"jpg","png","gif"});// 文件上传目录fileUpload.setFilePath("E:/project/apache.common.fileupload/");// 启用虚拟目录fileUpload.setIsVirdir(true);File ff = new File(request.getSession().getServletContext().getRealPath("/") + "temp/");fileUpload.setRepository(ff);// 限制文件上传大小fileUpload.setIsLimitSize(true);try {fileUpload=FileUploadUtil.fileUpload(request, fileUpload);} catch (Exception e) {e.printStackTrace();}request.setAttribute("msg","成功。");request.setAttribute("img", ff.toString().replace("\", "/")+"/" +fileUpload.getFileNameAll());request.getRequestDispatcher("/succ.jsp").forward(request, response);}}