Spring Boot Web在提供REST API下載的連結方式如下。
例如在Spring Boot專案的src/main/resources/static
目錄下有一個spring.png
圖檔。
在@RestController
類的GetMapping
方法設定下載路徑,取得圖檔寫到StreamingResponseBody
物件回傳,並使用HttpServletResponse.setHeader()
設定HTTP response header=
Content-Disposition: attachment; filename=<filename>
。
DemoController
package com.abc.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;
import javax.servlet.http.HttpServletResponse;
@RestController
public class DemoController {
@Value("classpath:static/spring.png")
private Resource resource;
@GetMapping("/download")
public StreamingResponseBody download(HttpServletResponse response) {
String filename = resource.getFilename();
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename);
return outputStream -> FileCopyUtils.copy(resource.getInputStream(), outputStream);
}
}
啟動專案在瀏覽器輸入url http://localhost:8080/download
即可下載spring.png
。
沒有留言:
張貼留言