網頁

2021/6/11

Spring Boot Web MVC REST API 下載檔案 download file

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


沒有留言:

張貼留言