文件上傳工具類

/**
 * 文件上傳工具類
 * 
 * @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_xyz
    private String fileName;

    // 文件保存目錄路徑
    private String savePath;
    // 文件保存目錄url
    private 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 + "/";
        // 文件保存目錄URL
        saveUrl = request.getContextPath() + "/" + basePath + "/";
        File uploadDir = new File(savePath);
        if (contentType == null || !contentType.startsWith("multipart")) {
            // TODO
            System.out.println("請求不包含multipart/form-data流");
            errorInfo = "請求不包含multipart/form-data流";
        } else if (maxSize < contentLength) {
            // TODO
            System.out.println("上傳文件大小超出文件最大大小");
            errorInfo = "上傳文件大小超出文件最大大小[" + maxSize + "]";
        } else if (!ServletFileUpload.isMultipartContent(request)) {
            // TODO
            errorInfo = "請選擇文件";
        } else if (!uploadDir.isDirectory()) {// 檢查目錄
            // TODO
            errorInfo = "上傳目錄[" + savePath + "]不存在";
        } else if (!uploadDir.canWrite()) {
            // TODO
            errorInfo = "上傳目錄[" + savePath + "]沒有寫權限";
        } else if (!extMap.containsKey(dirName)) {
            // TODO
            errorInfo = "目錄名不正確";
        } 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>();

        // 第一步:判斷request
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        // 第二步:解析request
        if (isMultipart) {
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // 閥值,超過這個值纔會寫到臨時目錄,否則在內存中
            factory.setSizeThreshold(1024 * 1024 * 10);
            factory.setRepository(new File(tempPath));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);

            upload.setHeaderEncoding("UTF-8");

            // 最大上傳限制
            upload.setSizeMax(maxSize);

            /* FileItem */
            List<FileItem> items = null;
            // Parse the request
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // 第3步:處理uploaded items
            if (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) { // 檢查文件大小
            // TODO
            error = "上傳文件大小超過限制";
        } 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.xxx
            fileUrl = 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;
    }

}
發佈了106 篇原創文章 · 獲贊 9 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章