通用的文件上傳方法

public String saveFileByIO(MultipartFile upload, String fileSeparator, String uploadPath, int flag) {
        if (upload == null) {
                return "";
        }
        InputStream in = null;
        try {
                in = upload.getInputStream();
        } catch (IOException e2) {
                log.debug(e2);

        }
        File dir = new File(uploadPath);
        if (!dir.exists()) {
                dir.mkdirs();
        }
        String fileName = upload.getOriginalFilename();
        if (flag == 1) {
                String uuidString = UUID.randomUUID().toString();
                String suffix = fileName.substring(fileName.indexOf("."));
                fileName = uuidString + (suffix != null ? suffix : "");
        }
        String relaPth = uploadPath + fileSeparator + fileName;
        File checkName = new File(relaPth);
        String reName = fileName;
        if (checkName.exists()) {
                String suffix = fileName.substring(fileName.indexOf("."));
                reName = fileName.substring(0, fileName.indexOf(".")) + "_" + DateUtil.getTodayTimeString().replace(" ", "_").replace(":", "-") + (suffix != null ? suffix : "");
                relaPth = uploadPath + fileSeparator + reName;
        }
        try {
                upload.transferTo(new File(relaPth));
        } catch (IllegalStateException e1) {
                log.debug(e1);
        } catch (IOException e1) {
                log.debug(e1);
        }
        return reName;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章