最近忙着都沒時間寫博客了,做了個項目,實現了下載功能,沒用到上傳,寫這篇文章也是順便參考學習了如何實現上傳,上傳和下載做一篇筆記吧
下載
主要有下面的兩種方式:
- 通過ResponseEntity
實現 - 通過寫HttpServletResponse的OutputStream實現
我只測試了ResponseEntity<InputStreamResource>
這種方法可行,另外一種方法請各位搜索資料。
我們在controller層中,讓某個方法返回ResponseEntity,之后,用戶打開這個url,就會直接開始下載文件
這里,封裝了一個方法export
,負責把File對象轉為ResponseEntity
public ResponseEntity<FileSystemResource> export(File file) {
if (file == null) {
return null;
}
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "attachment; filename=" + System.currentTimeMillis() + ".xls");//以時間命名文件,防止出現文件存在的情況,根據實際情況修改,我這里是返回一個xls文件
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("Last-Modified", new Date().toString());
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new FileSystemResource(file));
}
Controller
@RequestMapping("download")
public ResponseEntity<FileSystemResource> downloadFile() {
return export(new FIle());//這里返回調用export的結果
}
上傳
1.配置
spring boot使用上傳功能,得先進行配置,spring boot配置方式有兩種,一種是資源文件properties配置,另外一種方式則是yml配置
properties配置:
## MULTIPART (MultipartProperties)
# 開啟 multipart 上傳功能
spring.servlet.multipart.enabled=true
# 文件寫入磁盤的閾值
spring.servlet.multipart.file-size-threshold=2KB
# 最大文件大小
spring.servlet.multipart.max-file-size=200MB
# 最大請求大小
spring.servlet.multipart.max-request-size=215MB
yml配置:
spring:
servlet:
multipart:
enabled: true # 開啟 multipart 上傳功能
max-file-size: 200MB # 最大文件大小
max-request-size: 215MB # 最大文件請求大小
file-size-threshold: 2KB # 文件寫入磁盤的閾值
2.編寫url請求
controller
@PostMapping("/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "上傳失敗,請選擇文件";
}
String fileName = file.getOriginalFilename();
String filePath = "/Users/itinypocket/workspace/temp/";//文件上傳到服務器的路徑,根據實際情況修改
File dest = new File(filePath + fileName);
try {
file.transferTo(dest);
LOGGER.info("上傳成功");
return "上傳成功";
} catch (IOException e) {
LOGGER.error(e.toString(), e);
}
return "上傳失敗!";
}
多文件的話把參數改為MultipartFile[] fileList
即可
3.Web頁面上傳文件
注意,input標簽的name與url的請求參數名相同,上傳只能使用post請求
單個文件上傳:
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submFit" value="提交">
</form>
多個文件上傳:
input標簽加上multiple
屬性,即可一次選擇多個文件
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" multiple name="file"><br>
<input type="submit" value="提交">
</form>
4.Android端上傳文件
使用okhttp上傳文件
//新建一個File,Android中許多API回調的接口都是以Uri形式,轉為File即可
File file = new File(uri.getPath);
RequestBody filebody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
RequestBody body = new MultipartBody.Builder()
.addFormDataPart("file", file.getName(), filebody)
.build();
Request request = new Request.Builder()
.url("http://192.168.1.106:8080/webapp/fileUploadPage")
.post(body)
.build();
OkhttpClient okHttpClient=new OkHttpClient();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "請求失敗:" + e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
Log.e(TAG, "請求成功!");
}
});
參考鏈接:
spring boot文件下載
Spring Boot 文件上傳與下載
Spring Boot教程(十三):Spring Boot文件上傳
jsp 實現上傳 菜鳥教程