文件上傳下載action 和service

public class FileUploadAction extends BaseAction {

    /**
     * property serialVersionUID.
     */
    private static final long serialVersionUID = -3174042565144909773L;

    /**
     * property file.
     */
    private File file; // 上傳文件對象
    /**
     * property files.
     */
    private File[] files; // 上傳文件對象數組
    /**
     * property fileUpload.
     */
    private FileUpload fileUpload; // 文件上傳實體類對象
    /**
     * property sourceNames.
     */
    private String[] sourceNames; // 原文件名稱數組
    /**
     * property postfixs.
     */
    private String[] postfixs; // 原文件後綴名數組
    /**
     * property fileUploadService.
     */
    private FileUploadService fileUploadService; // 文件上傳邏輯
    /**
     * property result.
     */
    private String result;
    /**
     * 文件大小常量,1M
     */
    private static final double FILE_SIZE1 = 1024.0f;
    /**
     * 1G常量.
     */
    private static final double FILE_SIZE2 = FILE_SIZE1 * FILE_SIZE1;
    /**
     * 除後大小常量.
     */
    private static final int CUT_SIZE = 10;
    /**
     * 日誌.
     */
    private Logger log = LoggerFactory.getLogger(FileUploadAction.class);

    /**
     * 顯示上傳文件頁面.
     * @return 值.
     * @throws Exception 異常.
     */
    public String showUploadPage() throws Exception {
        SessionBean sb = getSessionBean();
        String empName = sb.getEmpName();
        request.setAttribute("empName", empName);
        String isMany = request.getParameter("isMany");
        request.setAttribute("isMany", StringUtils.isEmpty(isMany) ? false
                : Boolean.valueOf(isMany));
        String contextPath = request.getParameter("contextPath");
        request.setAttribute("contextPath",
                StringUtils.isEmpty(contextPath) ? "otherFile" : contextPath);
        return SUCCESS;
    }
    /**
     * 無用保留方法.
     * @return 空.
     */
    public String method1() {
        return null;
    }
    /**
     * 無用保留方法.
     * @return 空.
     */
    public String method2() {
        return null;
    }
    /**
     * 清空屬性.
     */
    private void clearProperty() {
        files = null;
        sourceNames = null;
        postfixs = null;
        file = null;
        fileUpload = null;
    }
    /**
     * 表單提交上傳文件(只能上傳一個).
     * .
     * @return null 值.
     * @throws Exception 異常.
     */
    public String submitFileUpload() throws Exception {
        // 設置相應字符編碼
        response.setContentType("text/html;charset=UTF-8");
        String message = "";
        if (filError2()) {
            message = PropertiesSon.getText("file_upload_message");
            response.getWriter().print(message);
        } else {
            // 得到當前用戶名
            fileUpload.setUserOfUpload(((SessionBean) session
                    .getAttribute("userinfo")).getEmpName());
            // 得到文件所屬文件夾名稱
            String contextPath = request.getParameter("contextPath");

            // 得到上傳文件的文件夾名稱 將上傳用戶封裝到文件上傳對象中
            fileUpload.setContextPath(contextPath);

            // 調用上傳文件邏輯
            FileUpload uploadFile = fileUploadService.uploadFileToServerAndDB(
                    file, fileUpload);
            log.info("表單提交上傳文件");
            clearProperty();
            // 回調javascript上傳成功方法
            message = "<script type='text/javascript'>window.parent.uploadSuccess('"
                    + uploadFile.getUrl() + "');</script>";
            response.getWriter().print(message);
        }
        return null;
    }

    /**
     * 表單提交上傳文件(只能上傳一個).
     * .
     * @return null 值.
     * @throws Exception 異常.
     */
    public String submitFileUpload2() throws Exception {
        // 設置相應字符編碼
        response.setContentType("text/html;charset=UTF-8");
        String message = "";
        if (filError2()) {
            message = PropertiesSon.getText("file_upload_message");
            response.getWriter().print(message);
        } else {
            // 得到當前用戶名
            fileUpload.setUserOfUpload(((SessionBean) session
                    .getAttribute("userinfo")).getEmpName());
            // 得到文件所屬文件夾名稱
            String contextPath = request.getParameter("contextPath");

            // 得到上傳文件的文件夾名稱 將上傳用戶封裝到文件上傳對象中
            fileUpload.setContextPath(contextPath);

            // 調用上傳文件邏輯
            FileUpload uploadFile = fileUploadService.uploadFileToServerAndDB(
                    file, fileUpload);
            log.info("表單提交上傳文件");
            clearProperty();
            // 回調javascript上傳成功方法
            response.getWriter().print(
                    "<script type='text/javascript'>window.parent.uploadSuccess('"
                            + uploadFile.getId() + "');</script>");
        }
        return null;
    }

    /**
     * 表單提交上傳文件(只能上傳一個)帶水印的文件上傳.
     * .
     * @return null 值.
     * @throws Exception 異常.
     */
    public String submitFileUpload3() throws Exception {
        // 設置相應字符編碼
        response.setContentType("text/html;charset=UTF-8");
        String message = "";
        if (filError2()) {
            message = PropertiesSon.getText("file_upload_message");
            response.getWriter().print(message);
        } else {
            // 得到當前用戶名
            fileUpload.setUserOfUpload(((SessionBean) session
                    .getAttribute("userinfo")).getEmpName());
            // 得到文件所屬文件夾名稱
            String contextPath = request.getParameter("contextPath");

            // 得到上傳文件的文件夾名稱 將上傳用戶封裝到文件上傳對象中
            fileUpload.setContextPath(contextPath);

            // 調用上傳文件邏輯
            FileUpload uploadFile = fileUploadService.uploadFileToServerAndDB3(
                    file, fileUpload);
            log.info("表單提交上傳文件");
            clearProperty();
            JSONObject jsonObj = CommonUtil.formatObjectToJson(uploadFile);
            // 回調javascript上傳成功方法
            response.getWriter().print(
                    "<script type='text/javascript'>window.parent.uploadSuccess("
                            + jsonObj + ");</script>");
        }
        return null;
    }

    /**
     * 播放視頻.
     * @return 值.
     * @throws Exception 異常.
     */
    public String playVideo() throws Exception {
        String id = request.getParameter("id");
        if (!verifyOr(id)) {
            boolean flag = CommonUtil.verifyNumber(id);
            if (flag) {
                FileUpload fileUpload = fileUploadService
                        .getFileUploadById(Long.parseLong(id));
                String videoUrl = fileUpload.getUrl();
                String imgUrl = videoUrl.substring(0,
                        videoUrl.lastIndexOf(".") + 1) + "jpg";
                request.setAttribute("videoUrl", videoUrl);
                request.setAttribute("imgUrl", imgUrl);
            }
        }
        return SUCCESS;
    }
    /**
     * 批量上傳文件.
     * @return 值.
     * @throws Exception 異常.
     */
    public String submitBetchFileUpload() throws Exception {
        // 得到超過20m的文件名稱字符串
        // 設置相應字符編碼
        response.setContentType("text/html;charset=UTF-8");
        // 判斷添加文件是否過大
        // 若文件大小合法
        if (fileError()) {
            clearProperty();
            // 若文件過大調用頁面uploadMessage(names) javascript函數
            response.getWriter()
                    .print("<script type='text/javascript'>window.parent.uploadMessage();</script>");
        } else {
            // 得到當前用戶名
            String empName = ((SessionBean) session.getAttribute("userinfo"))
                    .getEmpName();
            // 得到文件所屬文件夾名稱
            String contextPath = request.getParameter("contextPath");
            List<FileUpload> fileUploadList = fileUploadService
                    .batchFileUploadToServerAndDB(files, sourceNames, postfixs,
                            contextPath, empName);
            List<JSONObject> fileUploadJsonList = CommonUtil
                    .convertObjectListToJsonList(fileUploadList);

            // 調用頁面uploadSuccess(jsonList) javascript函數
            response.getWriter().print(
                    "<script type='text/javascript'>window.parent.parent.uploadSuccess('"
                            + fileUploadJsonList
                            + "');window.parent.disLoadImg('" + sumFileSize()
                            + "');</script>");
            clearProperty();
            log.info("批量上傳文件");
        }
        // 返回Null防止頁面跳轉
        return null;
    }

    /**
     * 下載文件.
     * @return 值.
     * @throws Exception 異常.
     */
    public String downloadFile() throws Exception {
        if (fileUpload == null || fileUpload.getId() == null) {
            return null;
        }
        // 根據編號查詢文件上傳對象
        fileUpload = fileUploadService.getFileUploadById(fileUpload.getId());
        if (fileUpload == null) {
            return null;
        }
        // 設置參數準備下載文件
        // 設置響應類型
        response.setContentType("application/x-download");
        // 原文件名稱
        String fileName = fileUpload.getSourceName() + "."
                + fileUpload.getPostfix();
        // 設置文件名稱字符編碼
//        fileName = URLEncoder.encode(fileName, "UTF-8");
        fileName = new String(fileName.getBytes("GBK"),
                "ISO8859-1");
        // 設置響應頭
        response.addHeader("Content-Disposition", "attachment;filename="
                + fileName);
        // 從屬性文件中得到服務器上傳文件所在主目錄
        String path = PropertiesSon.getText("server_uploaddir");
        // 得到文件所屬文件夾
        String filePath = fileUpload.getContextPath();
        // 得到服務器文件訪問路徑封裝到對象中
        String destPath = path + File.separator + filePath;
        // 得到服務器文件物理路徑
        String url = destPath + System.getProperty("file.separator")
                + fileUpload.getFileEditName();

        log.info("下載文件url:" + url);

        // 得到響應輸出流對象
        OutputStream output = response.getOutputStream();
        // 根據文件服務器物理路徑創建文件讀取對象
        FileInputStream fs = new FileInputStream(url);
        // 輸出文件
        byte[] b = new byte[NumberConstant.NUM1024];
        int i = 0;
        while ((i = fs.read(b)) > 0) {
            output.write(b, 0, i);
        }
        output.flush();
        fs.close();
        fs = null;
        output.close();
        output = null;
        log.info("下載文件");
        // null防止頁面跳轉
        return null;
    }
    /**
     * 驗證批量添加文件.
     * .
     * @return null 值.
     * @throws Exception 異常.
     */
    public Double sumFileSize() throws Exception {
        int fileCount = files.length;
        Double fileSize = 0.0;
        for (int i = 0; i < fileCount; i++) {
            File file = files[i];
            fileSize += file.length() / (FILE_SIZE2);
        }
        // 返回拼接好的超出20M的文件名稱字符串
        return fileSize;
    }
    /**
     * 判斷文件大小.
     * @return 標識.
     * @throws Exception 異常.
     */
    public Boolean fileError() throws Exception {
        int fileCount = files.length;
        for (int i = 0; i < fileCount; i++) {
            File file = files[i];
            if (file.length() / (FILE_SIZE2) >= CUT_SIZE) {
                return true;
            }
        }
        return false;
    }
    /**
     * 判斷文件大小.
     * @return 標識.
     */
    public Boolean filError2() {
        Double fileSize = file.length() / (FILE_SIZE2);
        return fileSize >= CUT_SIZE ? true : false;
    }
----------------------------------------------------------------------------------------------------------------------------------


public class FileUploadService extends BaseService {
    
    private Logger log = LoggerFactory.getLogger(FileUploadService.class);
    
    /**
     * 序列化碼.
     */
    private static final long serialVersionUID = -8240266986388761771L;
    /**
     * 文件大小常量,1M
     */
    private static final float FILE_SIZE = 1024.0f;
    /**
     * 異步調用視頻轉換類..
     */
    @Autowired
    private ConvertVideoUtility convertVideoUtil;
    /**
     * 根據編號查詢文件上傳對象..
     * @param id 文件上傳對象編號..
     * @return 文件上傳對象. 值.
     * @throws Exception 異常.
     */
    public FileUpload getFileUploadById(Long id) throws Exception {
        // 根據編號查詢文件上傳對象封裝成map集合
        String sql = "SELECT * FROM T_SYS_UPLOAD_FILE WHERE UF_ID=?";
        Map<String, Object> map = commonDao.getUniqueMap(sql, id);
        return getFileUploadByMap(map);
    }
    /**
     * 從Map中取出文件對象封裝成文件上傳對象.
     * @param map 從數據庫中查詢出來的map.
     * @return 文件上傳對象 值.
     * @throws Exception 異常.
     */
    public FileUpload getFileUploadByMap(Map<String, Object> map) throws Exception {
        if (map == null) {
            return null;
        }
        // 從map中取出數據封裝成文件上傳對象
        FileUpload fileUpload = new FileUpload();
        fileUpload.setId(Long.parseLong(map.get("UF_ID").toString()));
        fileUpload.setContextPath(map.get("CONTEXT_PATH").toString());
        fileUpload.setFileEditName(map.get("FILE_EDIT_NAME").toString());
        fileUpload.setFileSize(Float
                .parseFloat(map.get("FILE_SIZE").toString()));
        fileUpload.setMimeType(map.get("MIME_TYPE").toString());
        fileUpload.setPostfix(map.get("POSTFIX").toString());
        fileUpload.setProjectName(map.get("PROJECT_NAME").toString());
        fileUpload.setSourceName(map.get("SOURCE_NAME").toString());
        fileUpload.setUploadTime(DateUtil.parseToTimestamp(
                map.get("UPLOAD_TIME").toString(), DateUtil.format1));
        fileUpload.setUrl(map.get("URL").toString());
        fileUpload.setUserOfUpload(map.get("USER_OF_UPLOAD").toString());
        // 返回文件上傳對象
        return fileUpload;
    }
    /**
     * 上傳文件.
     * @param file 上傳的文件對象.
     * @param fileUpload 文件上傳實體類.
     * @return 封裝好的文件上傳實體類 值.
     * @throws Exception 異常.
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public FileUpload uploadFileToServerAndDB(File file, FileUpload fileUpload) throws Exception {
        // 封裝上傳文件對象並上傳文件到服務器中
        fileUpload = fillUpload(fileUpload, file);
        // 保存上傳文件對象
        commonDao.save(fileUpload);
        // 返回封裝好的上傳文件對象
        return fileUpload;
    }
    /**
     * 上傳文件.
     * @param file 上傳的文件對象.
     * @param fileUpload 文件上傳實體類.
     * @return 封裝好的文件上傳實體類 值.
     * @throws Exception 異常.
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public FileUpload uploadFileToServerAndDB3(File file, FileUpload fileUpload) throws Exception {
        // 封裝上傳文件對象並上傳文件到服務器中
        fileUpload = fillUpload3(fileUpload, file);
        // 保存上傳文件對象
        commonDao.save(fileUpload);
        // 返回封裝好的上傳文件對象
        return fileUpload;
    }

    /**
     * 批量上傳文件.
     * .
     * @param files 文件對象數組.
     * @param sourceNames 原文件名稱數組.
     * @param postfixs 文件後綴數組.
     * @param contextPath 文件所在服務器文件夾.
     * @param empName 上傳人名稱.
     * @return 上傳文件對象集合 值.
     * @throws Exception 異常.
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public List<FileUpload> batchFileUploadToServerAndDB(File[] files,
            String[] sourceNames, String[] postfixs, String contextPath,
            String empName) throws Exception {
        // 得到文件對象數組數量
        int count = files.length;
        // 準備一個新的集合封裝文件上傳對象
        List<FileUpload> fileUploadList = new ArrayList<FileUpload>();
        // 遍歷文件數組
        for (int i = 0; i < count; i++) {
            // 封裝文件上傳對象數據
            FileUpload fileUpload = new FileUpload();
            fileUpload.setContextPath(contextPath);
            fileUpload.setUserOfUpload(empName);
            fileUpload.setPostfix(postfixs[i]);
            fileUpload.setSourceName(sourceNames[i]);
            fileUpload = fillUpload(fileUpload, files[i]);
            fileUploadList.add(fileUpload);
        }
        // 批量保存文件上傳對象
        commonDao.saveOrUpdateAll(fileUploadList);
        // 返回文件上傳對象集合
        return fileUploadList;
    }
    /**
     * 批量上傳文件(加入containID與containType後).
     * @param files 文件對象數組.
     * @param sourceNames 原文件名稱數組.
     * @param postfixs 文件後綴數組.
     * @param contextPath 文件所在服務器文件夾.
     * @param empName 上傳人名稱.
     * @param containId 用到此文件的表ID.
     * @param containType 用到此文件的類型.
     * @return 上傳文件對象集合 值.
     * @throws Exception 異常.
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public List<FileUpload> batchFileUpload(File[] files,
            String[] sourceNames, String[] postfixs, String contextPath,
            String empName, Long containId, String containType) throws Exception {
        // 得到文件對象數組數量
        int count = files.length;
        // 準備一個新的集合封裝文件上傳對象
        List<FileUpload> fileUploadList = new ArrayList<FileUpload>();
        // 遍歷文件數組
        for (int i = 0; i < count; i++) {
            // 封裝文件上傳對象數據
            FileUpload fileUpload = new FileUpload();
            fileUpload.setContextPath(contextPath);
            fileUpload.setContainId(containId);
            fileUpload.setContainType(containType);
            fileUpload.setUserOfUpload(empName);
            fileUpload.setPostfix(postfixs[i]);
            fileUpload.setSourceName(sourceNames[i]);
            fileUpload = fillUpload(fileUpload, files[i]);
            fileUploadList.add(fileUpload);
        }
        // 批量保存文件上傳對象
        commonDao.saveOrUpdateAll(fileUploadList);
        // 返回文件上傳對象集合
        return fileUploadList;
    }
    /**
     * 準備文件上傳數據並傳輸..
     * @param fileUpload 上傳文件對象..
     * @param file 文件對象..
     * @return 文件上傳對象. 值.
     * @throws Exception 異常.
     */
    private FileUpload fillUpload(FileUpload fileUpload, File file) throws Exception {
        // 準備封裝數據
        // 準備文件上傳對象準備封裝
        FileUpload newFileUpload = new FileUpload();
        // 從屬性文件中得到服務器上傳文件所在主目錄
        String path = PropertiesSon.getText("server_uploaddir");
        // 得到文件所屬文件夾
        String filePath = fileUpload.getContextPath();
        // 得到服務器文件訪問路徑封裝到對象中
        String destPath = path + File.separator + filePath;
        // 根據文件路徑和文件主目錄去服務器端創建目錄
        FileUtil.mkDirForFilePath(destPath);
        // 得到當前時間戳並封裝到文件上傳對象中
        Timestamp uploadTime = new Timestamp(DateUtil.curentDate().getTime());
        // 得到文件mime_type
        String mimeType = new MimetypesFileTypeMap().getContentType(file);
        // 封裝
        newFileUpload.setUploadTime(uploadTime);
        // 將原文件名稱封裝到對象中
        newFileUpload.setSourceName(fileUpload.getSourceName());
        // 將文件後綴封裝到對象中
        newFileUpload.setPostfix(fileUpload.getPostfix());
        // 將文件訪問路徑封裝到對象中
        newFileUpload.setUrl(destPath);
        newFileUpload.setContextPath(filePath);
        // 將文件大小已KB爲單位的值封裝到對象中
        newFileUpload.setFileSize(file.length() / FILE_SIZE);
        // 將文件所屬項目名稱封裝到對象中
        newFileUpload.setProjectName("PPS_OA");
        // 將上傳人名稱封裝到對象中
        newFileUpload.setUserOfUpload(fileUpload.getUserOfUpload());
        // 將使用此文件的ID封裝到對象中
        newFileUpload.setContainId(fileUpload.getContainId());
        // 將用到此文件的類型封裝到對象中
        newFileUpload.setContainType(fileUpload.getContainType());
        // 給文件重新命名並封裝到對象中
        newFileUpload.setFileEditName(FileUtil.getfileName(
                newFileUpload.getSourceName(), newFileUpload.getPostfix()));
        // 將文件訪問路徑封裝到對象中
        String url = PropertiesSon.getText("server_accessdir")
                + newFileUpload.getContextPath() + "/"
                + CommonUtil.getURLEncode(newFileUpload.getFileEditName()
                        .substring(0, newFileUpload.getFileEditName().lastIndexOf("_")), "GBK")
                + newFileUpload.getFileEditName().substring(newFileUpload.getFileEditName().lastIndexOf("_"));
        newFileUpload.setUrl(url);
        // 得到文件的mime_type並封裝到對象中
        newFileUpload.setMimeType(mimeType);
        // 將原文件copy到服務器路徑中
        FileUtil.copyFile(file,
                new File(destPath + "/" + newFileUpload.getFileEditName()));
        // 返回上傳好的文件上傳對象
        return newFileUpload;
    }
    /**
     * 準備文件上傳數據並傳輸.
     * @param fileUpload 上傳文件對象.
     * @param file 文件對象.
     * @return 文件上傳對象 值.
     * @throws Exception 異常.
     */
    private FileUpload fillUpload3(FileUpload fileUpload, File file) throws Exception {
        // 準備封裝數據
        // 準備文件上傳對象準備封裝
        FileUpload newFileUpload = new FileUpload();
        // 從屬性文件中得到服務器上傳文件所在主目錄
        String path = PropertiesSon.getText("server_uploaddir");
        // 得到文件所屬文件夾
        String filePath = fileUpload.getContextPath();
        // 得到服務器文件訪問路徑封裝到對象中
        String destPath = path + File.separator + filePath;
        // 根據文件路徑和文件主目錄去服務器端創建目錄
        FileUtil.mkDirForFilePath(destPath);
        // 得到當前時間戳並封裝到文件上傳對象中
        Timestamp uploadTime = new Timestamp(DateUtil.curentDate().getTime());
        // 得到文件mime_type
        String mimeType = new MimetypesFileTypeMap().getContentType(file);
        // 封裝
        newFileUpload.setUploadTime(uploadTime);
        // 將原文件名稱封裝到對象中
        newFileUpload.setSourceName(fileUpload.getSourceName());
        // 將文件後綴封裝到對象中
        newFileUpload.setPostfix(fileUpload.getPostfix());
        // 將文件訪問路徑封裝到對象中
        newFileUpload.setUrl(destPath);
        newFileUpload.setContextPath(filePath);
        // 將文件大小已KB爲單位的值封裝到對象中
        newFileUpload.setFileSize(file.length() / FILE_SIZE);
        // 將文件所屬項目名稱封裝到對象中
        newFileUpload.setProjectName("PPS_OA");
        // 將上傳人名稱封裝到對象中
        newFileUpload.setUserOfUpload(fileUpload.getUserOfUpload());
        // 給文件重新命名並封裝到對象中
        newFileUpload.setFileEditName(FileUtil.getfileName(
                newFileUpload.getSourceName(), newFileUpload.getPostfix()));
        // 將文件訪問路徑封裝到對象中
        String url = PropertiesSon.getText("server_accessdir")
                + newFileUpload.getContextPath() + "/"
                + CommonUtil.getURLEncode(newFileUpload.getFileEditName()
                        .substring(0, newFileUpload.getFileEditName().lastIndexOf("_")), "GBK")
                + newFileUpload.getFileEditName().substring(newFileUpload.getFileEditName().lastIndexOf("_"));
        newFileUpload.setUrl(url);
        // 得到文件的mime_type並封裝到對象中
        newFileUpload.setMimeType(mimeType);
        // 將原文件copy到服務器路徑中
        FileUtil.copyFile(file,
                new File(destPath + "/" + newFileUpload.getFileEditName()));
        // 返回上傳好的文件上傳對象
        return newFileUpload;
    }

    //上傳文件最大大小
    /**
     * property fileMaxSize.
     */
    private static final Long FILE_MAX_SIZE = 20971520L;
    /**
     * @param request 請求對象.
     * @param fileUpload 文件上傳對象.
     * @return JsonMessage 封裝對象 值.
     * @throws IOException 文件IO異常.
     * @throws Exception 異常.
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Transactional(propagation = Propagation.REQUIRED)
    public JsonMessage saveFile(HttpServletRequest request,
            FileUpload fileUpload) throws IOException, Exception {
        JsonMessage jm = new JsonMessage();
        jm.setIsSuccess(false);
        // 得到當前時間戳並封裝到文件上傳對象中
        Timestamp uploadTime = new Timestamp(DateUtil.curentDate().getTime());
        fileUpload.setUploadTime(uploadTime);
        // 將文件所屬項目名稱封裝到對象中
        fileUpload.setProjectName("PPS_OA");
        // 獲取上傳文件服務器磁盤根路徑
        String distPath = PropertiesSon.getText("server_uploaddir");
        // 創建文件工廠
        DiskFileItemFactory fac = new DiskFileItemFactory();
        // 創建Servlet文件上傳對象
        ServletFileUpload upload = new ServletFileUpload(fac);
        // 封裝文件上傳編碼
        upload.setHeaderEncoding("UTF-8");
        List fileList = null;
        try {
            // 獲取請求中的所有參數集合
            fileList = upload.parseRequest((HttpServletRequest) request);
        } catch (FileUploadException ex) {
            jm.setError("獲取文件失敗!");
            return jm;
        }
        String contextPath = "otherFile";
        // 遍歷參數集合
        Iterator<FileItem> it = fileList.iterator();
        String savePath = "";
        File file = null;
        FileItem fileItem = null;
        boolean isVideo = false;
        while (it.hasNext()) {
            FileItem item = it.next();
            if (item.isFormField()) {
                // 得到上傳文件的文件夾名稱 將上傳用戶封裝到文件上傳對象中
                if ("contextPath".equals(item.getFieldName())) {
                    contextPath = item.getString();
                    fileUpload.setContextPath(contextPath);
                    // 拼接文件路徑
                    savePath = distPath + File.separator + contextPath;
                    File f1 = new File(savePath);
                    // 驗證文件夾是否存在
                    if (!f1.exists()) {
                        f1.mkdirs();
                    }
                }
                //得到上傳用戶姓名
                if ("empName".equals(item.getFieldName())) {
                    // 獲取用戶session中封裝的信息對象
                    String empName = item.getString();
                    fileUpload.setUserOfUpload(empName);
                }
                //得到是否上傳的是視頻
                if ("isVideo".equals(item.getFieldName())) {
                    isVideo = Boolean.valueOf(item.getString());
                }
            }
        }
        // 遍歷參數集合
        Iterator<FileItem> it2 = fileList.iterator();
        while (it2.hasNext()) {
            FileItem item = it2.next();
            // 判斷參數是否不是普通form表單項
            if (!item.isFormField()) {
                // 封裝文件上傳對象
                String  name = item.getName();
                if (name == null || "".equals(name.trim())) {
                    continue;
                }
                fileUpload.setSourceName(name);
                //判斷文件大小
                Long size = item.getSize();
                if (size > FILE_MAX_SIZE && !isVideo) {
                    jm.setError("上傳文件不能超過20M!");
                    return jm;
                }
                fileUpload.setFileSize(size / FILE_SIZE);
                String type = item.getContentType();
                fileUpload.setMimeType(type);
                // 擴展名格式
                if (name.lastIndexOf(".") >= 0) {
                    String postfix = name.substring(name.lastIndexOf(".") + 1);
                    String sourceName = name.substring(0, name.lastIndexOf("."));
                    fileUpload.setSourceName(sourceName);
                    fileUpload.setPostfix(postfix);
                } else {
                    fileUpload.setSourceName(name);
                    fileUpload.setPostfix("");
                }
                do {
                    // 修改上傳文件名稱
                    fileUpload
                            .setFileEditName(FileUtil.getfileName(
                                    fileUpload.getSourceName(),
                                    fileUpload.getPostfix()).replace("$", "NZ"));
                    // 獲取文件服務器新路徑
                    String newPath = savePath + File.separator
                            + fileUpload.getFileEditName();
                    // 拼接文件訪問路徑
                    String url = PropertiesSon.getText("server_accessdir")
                            + fileUpload.getContextPath()
                            + "/"
                            + CommonUtil.getURLEncode(
                                    fileUpload.getFileEditName().substring(0,
                                            fileUpload.getFileEditName().lastIndexOf("_")), "GBK")
                            + fileUpload.getFileEditName().substring(
                                    fileUpload.getFileEditName().lastIndexOf("_"));
                    fileUpload.setUrl(url);
                    // 根據文件路徑創建File對象
                    file = new File(newPath);
                    fileItem = item;
                } while (file.exists());
                //將文件寫到目錄下
                try {
                    fileItem.write(file);
                } catch (Exception e) {
                    log.error(CommonUtil.getErrorMessage(e));
                    jm.setError("上傳失敗!");
                    return jm;
                }
            }
        }
        log.info("上傳文件成功!");
        commonDao.save(fileUpload);
        jm.setIsSuccess(true);
        jm.setMessage(CommonUtil.formatObjectToJson(fileUpload).toString());
        if (isVideo) {
            //如果是視頻,異步進行視頻格式轉換,並截取視頻默認預覽圖片
            convertVideoUtil.convertVideo(fileUpload);
        }
        return jm;
    }
    /**
     * @return the convertVideoUtil
     */
    public ConvertVideoUtility getConvertVideoUtil() {
        return convertVideoUtil;
    }
    /**
     * @param convertVideoUtil the convertVideoUtil to set
     */
    public void setConvertVideoUtil(ConvertVideoUtility convertVideoUtil) {
        this.convertVideoUtil = convertVideoUtil;
    }
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章