1. 程式人生 > >java檔案上傳至伺服器與檔案的刪除

java檔案上傳至伺服器與檔案的刪除

一、檔案上傳(到伺服器中)程式碼如下:

    /**
     * 上傳檔案
     * @param file 檔案
     * @param request HttpServletRequest
     * @return 返回檔案基本資訊
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData uploadImg(@RequestParam("file") MultipartFile file,
            HttpServletRequest request) {
        if (file == null) {
            return ResponseData.notFound().putDataValue("key", "file is null");
        }
        FileAttribute attribute = new FileAttribute();
        //獲取上傳檔案的原名
        String fileName = file.getOriginalFilename();
        //獲取檔案字尾
        String suffix = getFileNameWithSuffix(fileName);
        String filePath = "";
        try {
            //得到上傳路徑
            filePath = URLDecoder.decode(getUploadPath(request), "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        String fileUploadName = new Date().getTime() + "." + suffix;
        //物理路徑
        String fileUploadPath = filePath + fileUploadName;
        attribute.setSuffix(suffix);
        attribute.setName(fileUploadName);
        //        //windows路徑‘\\’替換為‘/’
        //        String path = StringUtils.substringAfterLast(fileUploadPath, "webapp");
        //        if (path.contains("\\")) {
        //            path = filePath.replace("\\", "/");
        //        }
        attribute.setUrl(fileUploadPath);
        if (StringUtils.isNotBlank(fileName)) {
            try {
                File dir = new File(filePath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File serverFile = new File(fileUploadPath);
                file.transferTo(serverFile);
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseData.notFound().putDataValue("key",
                        "uploadimg fail");
            }
            /**
             * 專案伺服器地址路徑
             */
            String projectServerPath = request.getScheme() + "://" + request.getServerName() + ":" 
                           + request.getServerPort() + request.getContextPath() + "/upload/";
            System.out.println(projectServerPath);
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("fileName", fileName);
            map.put("suffix", suffix);
            map.put("size", file.getSize());
            map.put("url", projectServerPath + fileUploadName);
            return ResponseData.ok().putDataValue("info", map);
        } else {
            return ResponseData.notFound().putDataValue("key",
                    "File suffix is invalid");
        }
    }
    //得到上傳路徑
    private String getUploadPath(HttpServletRequest request) {
        String path = "";
        int length = 0;
        int i = 0;
        String orginionPath = "";
        //判斷是什麼系統
        if ("\\".equals(File.separator)) {
            path = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1);
            length = request.getContextPath().substring(1).length();
            i = path.indexOf(request.getContextPath().substring(1));
            orginionPath = path.substring(0, i + length);
            orginionPath = orginionPath.replace("/", File.separator);
            orginionPath = orginionPath + File.separator + "src" + File.separator + "main"
                + File.separator + "webapp" + File.separator + "upload" + File.separator;
        } else {
            System.out.println("----linux-----");
            path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
            length = request.getContextPath().length();
            i = path.indexOf(request.getContextPath().substring(1));
            orginionPath = path.substring(0, i + length);
            orginionPath = orginionPath.replace("\\", File.separator);
            orginionPath = orginionPath + File.separator + "src" + File.separator + "main"
                  + File.separator + "webapp" + File.separator + "upload" + File.separator;
            orginionPath = orginionPath.substring(5);
            System.out.println("orginionPath=" + orginionPath);
        }
        return orginionPath;
    }

    /**
     * 保留檔名及字尾
     */
    public String getFileNameWithSuffix(String pathandname) {
        File file = new File(pathandname);
        String fileName = file.getName();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return suffix;
    }

    /**
     * 圖片限制
     *
     * @param fileName 全路徑
     * @return
     */
    public boolean checkSuffix(String fileName) {
        String suffix = getFileNameWithSuffix(fileName);
        if (suffix.equals("jpg") || suffix.equals("png")) {
            return true;
        }
        return false;
    }

    public class FileAttribute {
        private String name;
        private String suffix;
        private String url;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSuffix() {
            return suffix;
        }

        public void setSuffix(String suffix) {
            this.suffix = suffix;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }

二、檔案刪除

在刪除檔案之前必須首先得到檔案的絕對路徑,根據系統在本地檔案中在的路徑進行檔案的刪除,具體程式碼如下:

                        //取得當前主機存放專案的絕對路徑
                        String workPath = System.getProperty("user.dir");
                        //得到檔名
                        String fileUrl = bookShareItem.getFileUrl();
                        int beginIndex = fileUrl.lastIndexOf("/");
                        int endIndex = fileUrl.length();
                        String substring = fileUrl.substring(beginIndex + 1, endIndex);
                        //獲得檔案存放的絕對路徑
                        String fullFilePath = workPath + File.separator
                                + "aa\\bb\\cc\\upload" + File.separator
                                + substring;
                        //刪除檔案
                        File deleteFile = new File(fullFilePath);
                        if (deleteFile.exists() && deleteFile.isFile()
                                && deleteFile.delete() == true) {
                            fileFlag = true;
                        }