在開發後端程式時,我們常常需要開一個 RESTful API,讓前端(如 Angular、React)可以下載檔案。用 Spring Boot 的 StreamingResponseBody 可以輕鬆地實作檔案下載功能。
如下方的程式碼,只要用 FileCopyUtils.copy() 將 InputStream 的資料複製到 StreamingResponseBody 的 OutputStream 就可以了!
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
@RestController
@RequestMapping("/logs")
public class LogController {
@GetMapping(value = "/download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public ResponseEntity<StreamingResponseBody> downloadLog() throws FileNotFoundException {
InputStream inputStream = new FileInputStream("/path/to/log");
StreamingResponseBody body = outputStream -> FileCopyUtils.copy(inputStream, outputStream);
return ResponseEntity.ok()
.header("Content-Disposition", "attachment;filename=server.log")
.body(body);
}
}現在你可以試著用瀏覽器開 http://localhost:8080/logs/download,就會直接下載檔案!









