REST with Spring Boot 2
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Download File
REST 的 Download 可以用 GET 和 POST 實做。
- method 前面的
@RequestMapping
和 GET 或 POST 的用法類似,不過建議把produces
拿掉(因為已經不是回傳 JSON 了) - method 回傳的參數改為
ResponseEntity<byte[]>
- 回傳的時候使用下面的做法
// 使用 GET 的 download API,我們可以設定 attachment header,這樣用瀏覽器直接開啟連結就會直接跳到下載,並檔名自動帶入我們設定的檔案名稱
@RequestMapping(value = "/downloadGet", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadGet(@RequestParam("param") String param) {
// get your file's bytes & file name
byte[] fileBytes = new byte[];
String fileName = "File Name";
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", encodedFileName);
return new ResponseEntity<>(fileBytes, headers, HttpStatus.OK);
}
// 使用 POST 的話就不用特別做了,因為無法使用瀏覽器直接打開,attachment header 就沒有用了。
@RequestMapping(value = "/downloadPost", method = RequestMethod.POST)
public ResponseEntity<byte[]> downloadPost(@RequestBody QueryTO queryTO) {
// get your file's bytes & file name
byte[] fileBytes = new byte[];
String fileName = "File Name";
return new ResponseEntity<>(fileBytes, HttpStatus.OK);
}
檔名如果有非 ASCII 字元會發生什麼事?特殊字元呢?試試看如何讓 Chrome 可以正確的上傳和下載中文檔名的檔案吧。
下面的練習,請試著根據 TODO 的資訊完成對應的 download REST API。
Complete the controller to Download File.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.example.training.rest;
public class QuizController06 {
/* TODO:
1. add GET REST API with url "/restQuiz06"
2. 1 GET parameter with name "filePathName"
* filePathName example: "/data/hello.txt"
3. retrieve file by filePathName, begins with "./files" folder
* for example, if filePathName = "/data/hello.txt", final file path will be "./files/data/hello.txt"
4. return file bytes
5. Only files under ./files/ can be downloaded, if not, return HTTP CODE 403
6. If folder or file not found, return HTTP CODE 404
7. If filePathName is a folder, return HTTP CODE 404
*/
}
Enter to Rename, Shift+Enter to Preview
Suggested playgrounds
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content