SpringBoot下檔案上傳與下載的實現
阿新 • • 發佈:2018-12-23
本文歡迎轉載,轉載請註明出處,謝謝~(作者:喝酒不騎馬 Colton_Null)
from CSDN
SpringBoot後臺如何實現檔案上傳下載?
最近做的一個專案涉及到檔案上傳與下載。前端上傳採用百度webUploader外掛。有關該外掛的使用方法還在研究中,日後整理再記錄。本文主要介紹SpringBoot後臺對檔案上傳與下載的處理。
單檔案上傳
// 單檔案上傳
@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 "上傳失敗";
}
如果想要修改檔案路徑及檔名,修改filePath以及fileName即可。
多檔案上傳
//多檔案上傳
@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;
}
MultipartConfig配置
可以通過MultipartConfig配置類對檔案上傳進行全域性控制。
@Configuration
public class MultipartConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// 置檔案大小限制 ,超出此大小頁面會丟擲異常資訊
factory.setMaxFileSize("2MB"); //KB,MB
// 設定總上傳資料總大小
factory.setMaxRequestSize("20MB");
// 設定檔案臨時資料夾路徑
// factory.setLocation("E://test//");
// 如果檔案大於這個值,將以檔案的形式儲存,如果小於這個值檔案將儲存在記憶體中,預設為0
// factory.setMaxRequestSize(0);
return factory.createMultipartConfig();
}
}
注意事項
前後端檔案傳輸格式應為 multipart/form-data