1. 程式人生 > 實用技巧 >springboot檔案上傳刪除下載

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; }