SpringBoot文件上傳、刪除及下載


SpringBoot文件上傳、刪除及下載

最近的項目中,需要將文件保存項目的根目錄路徑下,特此記錄下文件的操作:

文件上傳

    /**
     * 文件上傳(相對路徑)
     *
     * @param uploadFile 文件
     * @param request    參數
     * @return 文件路徑
     */
    public static String upload(MultipartFile uploadFile, HttpServletRequest request) {
        // 項目根路徑下的目錄
        final String UPLOAD_PATH_PREFIX = "/static/resources/upload/app";
        //訪問目錄
        final String DOWNLOAD_PATH_PREFIX = "/resources/upload/app";
        if (uploadFile.isEmpty()) {
            //返回選擇文件提示
            return "請選擇上傳文件";
        }
        //項目根目錄的絕對路徑 + 指定文件夾路徑
        String realPath = System.getProperty("user.dir") + UPLOAD_PATH_PREFIX;
        logger.info("-----------上傳文件保存的路徑【" + realPath + "】-----------");
        //存放上傳文件的文件夾
        File file = new File(realPath);
        logger.info("-----------輸出文件夾絕對路徑 -- 這里的絕對路徑是相當於當前項目的路徑【" + file.getAbsolutePath() + "】-----------");
        if (!file.isDirectory()) {
            //遞歸生成文件夾
            file.mkdirs();
        }
        //獲取原始的名字
        String oldName = uploadFile.getOriginalFilename();
        logger.info("-----------文件原始的名字【" + oldName + "】-----------");
        //原文件名 + 時間戳 + 文件類型
        String newName = oldName.substring(0, oldName.lastIndexOf(".")) + System.currentTimeMillis() + oldName.substring(oldName.lastIndexOf("."));
        logger.info("-----------文件要保存后的新名字【" + newName + "】-----------");
        try {
            //構建真實的文件路徑
            File newFile = new File(file.getAbsolutePath() + File.separator + newName);
            //轉存文件到指定路徑,如果文件名重復的話,將會覆蓋掉之前的文件,這里是把文件上傳到 “絕對路徑”
            uploadFile.transferTo(newFile);
            //訪問前綴方式一
//            String filePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + DOWNLOAD_PATH_PREFIX + "/"  + newName;
            //訪問前綴方式二
//            StringBuffer url = request.getRequestURL();
//            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
            //不包含訪問前綴
            String filePath = DOWNLOAD_PATH_PREFIX + "/" + newName;
            logger.info("-----------【" + filePath + "】-----------");
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上傳失敗!";
    }

文件刪除

    /**
     * 文件刪除
     * 
     * @param filePath 文件路徑
     * @return false、true
     */
    public static Boolean delete(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
            System.out.println("===========刪除成功=================");
            return true;
        } else {
            System.out.println("===============刪除失敗==============");
            return false;
        }
    }

文件下載

文件下載功能參考博客:https://www.jianshu.com/p/85017f5ecba1

/**
* 文件下載
*
* @param response 聲明response
* @return false、true
*/
public Boolean downloadFile(HttpServletResponse response) {
    String fileName = "redis-serve1599809147700.exe";// 文件名
    if (fileName != null) {
        //設置文件路徑
        File file = new File(System.getProperty("user.dir") + "/static/resources/upload/app/redis-serve1599809147700.exe");
        //File file = new File(realPath , fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 設置強制下載不打開
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設置文件名
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return false;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM