首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java通用文件下传工具类

2012-08-24 
java通用文件上传工具类目的:为一劳永逸,经过多方参考,特写此java通用文件上传工具类--------------------

java通用文件上传工具类

目的:

为一劳永逸,经过多方参考,特写此java通用文件上传工具类

------------------------------------

?

所需jar包

commons-fileupload-1.2.2.jar

commons-io-2.0.1.jar

------------------------------------

代码说明:

上传文件默认保存路径为:

.../basePath/dirName/yyyyMMdd/fileName.abc

.../upload/images/yyyyMMdd/yyyyMMddHHmmss_xyz.abc(xyz为0-1000之内的随机数,abc为文件名)

其中:

basePath-->upload

dirName-->images

fileName-->若不指定文件名,默认为yyyyMMddHHmmss_xyz

extMap-->允许的扩展名,默认见代码中的构造方法

注:extMap中的key中必须含有dirName

?

------------------------------------

实现代码:

package com.ln.ydc.blog.util;import java.io.File;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Arrays;import java.util.Date;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Random;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;/** * 文件上传工具类 *  * @author yangdc * @date Apr 18, 2012 *  * <pre> * </pre> */public class UploadUtils {/** * 表单字段常量 */public static final String FORM_FIELDS = "form_fields";/** * 文件域常量 */public static final String FILE_FIELDS = "file_fields";// 最大文件大小private long maxSize = 1000000;// 定义允许上传的文件扩展名private Map<String, String> extMap = new HashMap<String, String>();// 文件保存目录相对路径private String basePath = "upload";// 文件的目录名private String dirName = "images";// 上传临时路径private static final String TEMP_PATH = "/temp";private String tempPath = basePath + TEMP_PATH;// 若不指定则文件名默认为 yyyyMMddHHmmss_xyzprivate String fileName;// 文件保存目录路径private String savePath;// 文件保存目录urlprivate String saveUrl;// 文件最终的url包括文件名private String fileUrl;public UploadUtils() {// 其中images,flashs,medias,files,对应文件夹名称,对应dirName// key文件夹名称// value该文件夹内可以上传文件的后缀名extMap.put("images", "gif,jpg,jpeg,png,bmp");extMap.put("flashs", "swf,flv");extMap.put("medias", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");extMap.put("files", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");}/** * 文件上传 *  * @param request * @return infos info[0] 验证文件域返回错误信息 info[1] 上传文件错误信息 info[2] savePath info[3] saveUrl info[4] fileUrl */@SuppressWarnings("unchecked")public String[] uploadFile(HttpServletRequest request) {String[] infos = new String[5];// 验证infos[0] = this.validateFields(request);// 初始化表单元素Map<String, Object> fieldsMap = new HashMap<String, Object>();if (infos[0].equals("true")) {fieldsMap = this.initFields(request);}// 上传List<FileItem> fiList = (List<FileItem>) fieldsMap.get(UploadUtils.FILE_FIELDS);if (fiList != null) {for (FileItem item : fiList) {infos[1] = this.saveFile(item);}infos[2] = savePath;infos[3] = saveUrl;infos[4] = fileUrl;}return infos;}/** * 上传验证,并初始化文件目录 *  * @param request */private String validateFields(HttpServletRequest request) {String errorInfo = "true";// boolean errorFlag = true;// 获取内容类型String contentType = request.getContentType();int contentLength = request.getContentLength();// 文件保存目录路径savePath = request.getSession().getServletContext().getRealPath("/") + basePath + "/";// 文件保存目录URLsaveUrl = request.getContextPath() + "/" + basePath + "/";File uploadDir = new File(savePath);if (contentType == null || !contentType.startsWith("multipart")) {// TODOSystem.out.println("请求不包含multipart/form-data流");errorInfo = "请求不包含multipart/form-data流";} else if (maxSize < contentLength) {// TODOSystem.out.println("上传文件大小超出文件最大大小");errorInfo = "上传文件大小超出文件最大大小[" + maxSize + "]";} else if (!ServletFileUpload.isMultipartContent(request)) {// TODOerrorInfo = "请选择文件";} else if (!uploadDir.isDirectory()) {// 检查目录// TODOerrorInfo = "上传目录[" + savePath + "]不存在";} else if (!uploadDir.canWrite()) {// TODOerrorInfo = "上传目录[" + savePath + "]没有写权限";} else if (!extMap.containsKey(dirName)) {// TODOerrorInfo = "目录名不正确";} else {// .../basePath/dirName/// 创建文件夹savePath += dirName + "/";saveUrl += dirName + "/";File saveDirFile = new File(savePath);if (!saveDirFile.exists()) {saveDirFile.mkdirs();}// .../basePath/dirName/yyyyMMdd/SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");String ymd = sdf.format(new Date());savePath += ymd + "/";saveUrl += ymd + "/";File dirFile = new File(savePath);if (!dirFile.exists()) {dirFile.mkdirs();}// 获取上传临时路径tempPath = request.getSession().getServletContext().getRealPath("/") + tempPath + "/";File file = new File(tempPath);if (!file.exists()) {file.mkdirs();}}return errorInfo;}/** * 处理上传内容 *  * @param request * @param maxSize * @return */@SuppressWarnings("unchecked")private Map<String, Object> initFields(HttpServletRequest request) {// 存储表单字段和非表单字段Map<String, Object> map = new HashMap<String, Object>();// 第一步:判断requestboolean isMultipart = ServletFileUpload.isMultipartContent(request);// 第二步:解析requestif (isMultipart) {// Create a factory for disk-based file itemsDiskFileItemFactory factory = new DiskFileItemFactory();// 阀值,超过这个值才会写到临时目录,否则在内存中factory.setSizeThreshold(1024 * 1024 * 10);factory.setRepository(new File(tempPath));// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8");// 最大上传限制upload.setSizeMax(maxSize);/* FileItem */List<FileItem> items = null;// Parse the requesttry {items = upload.parseRequest(request);} catch (FileUploadException e) {// TODO Auto-generated catch blocke.printStackTrace();}// 第3步:处理uploaded itemsif (items != null && items.size() > 0) {Iterator<FileItem> iter = items.iterator();// 文件域对象List<FileItem> list = new ArrayList<FileItem>();// 表单字段Map<String, String> fields = new HashMap<String, String>();while (iter.hasNext()) {FileItem item = iter.next();// 处理所有表单元素和文件域表单元素if (item.isFormField()) { // 表单元素String name = item.getFieldName();String value = item.getString();fields.put(name, value);} else { // 文件域表单元素list.add(item);}}map.put(FORM_FIELDS, fields);map.put(FILE_FIELDS, list);}}return map;}/** * 保存文件 *  * @param obj *            要上传的文件域 * @param file * @return */private String saveFile(FileItem item) {String error = "true";String fileName = item.getName();String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();if (item.getSize() > maxSize) { // 检查文件大小// TODOerror = "上传文件大小超过限制";} else if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {// 检查扩展名error = "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。";} else {String newFileName;if ("".equals(fileName.trim())) {SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;} else {newFileName = fileName + "." + fileExt;}// .../basePath/dirName/yyyyMMdd/yyyyMMddHHmmss_xxx.xxxfileUrl = saveUrl + newFileName;try {File uploadedFile = new File(savePath, newFileName);item.write(uploadedFile);/* * FileOutputStream fos = new FileOutputStream(uploadFile); // 文件全在内存中 if (item.isInMemory()) { fos.write(item.get()); } else { InputStream is = item.getInputStream(); byte[] buffer = * new byte[1024]; int len; while ((len = is.read(buffer)) > 0) { fos.write(buffer, 0, len); } is.close(); } fos.close(); item.delete(); */} catch (IOException e) {e.printStackTrace();System.out.println("上传失败了!!!");} catch (Exception e) {e.printStackTrace();}}return error;}/** **********************get/set方法********************************* */public String getSavePath() {return savePath;}public String getSaveUrl() {return saveUrl;}public long getMaxSize() {return maxSize;}public void setMaxSize(long maxSize) {this.maxSize = maxSize;}public Map<String, String> getExtMap() {return extMap;}public void setExtMap(Map<String, String> extMap) {this.extMap = extMap;}public String getBasePath() {return basePath;}public void setBasePath(String basePath) {this.basePath = basePath;tempPath = basePath + TEMP_PATH;}public String getDirName() {return dirName;}public void setDirName(String dirName) {this.dirName = dirName;}public String getTempPath() {return tempPath;}public void setTempPath(String tempPath) {this.tempPath = tempPath;}public String getFileUrl() {return fileUrl;}public String getFileName() {return fileName;}public void setFileName(String fileName) {this.fileName = fileName;}}

?

?

?

?

?

?

?

?

热点排行