**#使用springboot進行檔案上傳和下載**
阿新 • • 發佈:2018-11-19
使用springboot進行檔案上傳和下載
##檔案下載功能的實現思路:
1.獲取要下載的檔案的絕對路徑
2.獲取要下載的檔名
3.設定content-disposition響應頭控制瀏覽器以下載的形式開啟檔案
4.獲取要下載的檔案輸入流
5.建立資料緩衝區//緩衝區解釋見下文
6.通過response物件獲取OutputStream流
7.將FileInputStream流寫入到buffer緩衝區
單檔案上傳
// 單檔案上傳 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { try { if (file.isEmpty()) { return "檔案為空"; } // 獲取檔名 String fileName = file.getOriginalFilename(); logger.info("上傳的檔名為:" + fileName); // 獲取檔案的字尾名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); logger.info("檔案的字尾名為:" + suffixName); // 設定檔案儲存路徑 String filePath = "D://aim//"; String path = filePath + fileName + suffixName; File dest = new File(path); // 檢測是否存在目錄 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs();// 新建資料夾 } file.transferTo(dest);// 檔案寫入 return "上傳成功"; } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "上傳失敗"; }
多檔案上傳
//多檔案上傳 @RequestMapping(value = "/uploadMore", method = RequestMethod.POST) @ResponseBody public String handleFileUpload(HttpServletRequest request) { List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file"); MultipartFile file = null; BufferedOutputStream stream = null; for (int i = 0; i < files.size(); ++i) { file = files.get(i); String filePath = "D://aim//"; if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); stream = new BufferedOutputStream(new FileOutputStream( new File(filePath + file.getOriginalFilename())));//設定檔案路徑及名字 stream.write(bytes);// 寫入 stream.close(); } catch (Exception e) { stream = null; return "第 " + i + " 個檔案上傳失敗 ==> " + e.getMessage(); } } else { return "第 " + i + " 個檔案上傳失敗因為檔案為空"; } } return "上傳成功"; }
檔案下載
//檔案下載相關程式碼 @RequestMapping("/download") public String downloadFile(HttpServletRequest request, HttpServletResponse response) { String fileName = "aim_test.txt";// 設定檔名,根據業務需要替換成要下載的檔名 if (fileName != null) { //設定檔案路徑 String realPath = "D://aim//" 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); } System.out.println("success"); } 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 null; }
表單頁面
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Getting Started: Serving Web Content</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p>Get your greeting <a href="/greeting">here</a></p>
<form action="/upload" method="POST" enctype="multipart/form-data">
檔案:<input type="file" name="test"/>
<input type="submit" />
</form>
<a href="/download">下載test</a>
<p>多檔案上傳</p>
<form method="POST" enctype="multipart/form-data" action="/batch/upload">
<p>檔案1:<input type="file" name="file" /></p>
<p>檔案2:<input type="file" name="file" /></p>
<p><input type="submit" value="上傳" /></p>
</form>
</html>
如圖所示
ps:如果下載的檔案出現亂碼問題
希望對你有所幫助!