java - 如何将 HttpServletResponse 响应获取到 Spring Boot 的 REST Controller 中?

标签 java spring rest spring-boot

我正在努力将 HttpServletResponse 响应 放入 Spring Boot 的 REST Controller 中。背后的目的是我想从 REST Controller 返回一个文件流。

这是代码。

@Component
@Api(value = "/api/1/download", description = "act upon selected file.")
@Path("/api/1/download")
@Consumes(MediaType.APPLICATION_JSON)
@RestController
public class DownloadResource {
    private final Logger log = LoggerFactory.getLogger(DownloadResource.class);

    @Autowired
    HttpServletResponse response;

    @ApiOperation(value = "Download a selected file", notes = "allows to download a selected file")
    @Path("/downloadFile")
    @POST
    @Autowired
    public void download(Object fileObject)  {
        String name = (String) ((LinkedHashMap) fileObject).get("path");
        response.setContentType("text/plain");
        response.addHeader("Content-Disposition", "attachment; filename=abcd.txt");
        try
        {
            Files.copy(Paths.get(name), response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

    }

}

文件既没有下载也没有抛出错误。请帮忙建议。谢谢。

最佳答案

试一试。我明白你想做什么吗?

@SpringBootApplication
@RestController
public class FiledownloadApplication {

    public static void main(String[] args) {
        SpringApplication.run(FiledownloadApplication.class, args);
    }


    @PostMapping("/downloadFile")
    public ResponseEntity<FileSystemResource> download(@RequestBody FileDownload fileDownload) throws IOException {
        String path = fileDownload.getPath();
        FileSystemResource fileSystemResource = new FileSystemResource(path);
        return new ResponseEntity<>(fileSystemResource, HttpStatus.OK);
    }

    class FileDownload {

        String path;

        public FileDownload() {
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }
    }
}

关于java - 如何将 HttpServletResponse 响应获取到 Spring Boot 的 REST Controller 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43932163/

相关文章:

java - post查询的动态过滤条件

java - 如何将 Spring 事务传播到另一个线程?

java - 如何在没有 XML 的情况下使用 Spring 启动 H2 WebServer?

java - 在Java中通过键名解析JSON

c# - 在没有单独方法的情况下在 RESTful WCF 中混合 XML 和 JSON

java - 导入 libcore.io.DiskLruCache 失败

java - 如何避免使用 log4j 丢失日志

java - 为 Spring Boot 应用程序构建了两个 JAR

spring - 为什么代理不用于 Autowiring

rest - SharePoint REST API 筛选器仅基于今天的日期而不是时间。 (类似于 CAML 查询中的 IncludeTimeValue=False)