Back
Close

REST with Spring Boot 2

Nierrrrrrr
995 views

Download File

REST 的 Download 可以用 GET 和 POST 實做。

  1. method 前面的 @RequestMapping 和 GET 或 POST 的用法類似,不過建議把 produces 拿掉(因為已經不是回傳 JSON 了)
  2. method 回傳的參數改為 ResponseEntity<byte[]>
  3. 回傳的時候使用下面的做法
// 使用 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.
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
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants