使用Spring Boot提供压缩文件

问题描述 投票:3回答:1

我正在尝试使用Spring Boot REST提供压缩的日志文件。文件已经被压缩,我不需要将其压缩。浏览器应将其解压缩并显示纯文本。

根据我搜索过的信息,我需要完成两项工作:

  • 在请求标头中设置以下内容:'Accept-Encoding': 'gzip'
  • 在响应头中设置以下内容:'Content-Encoding': 'gzip'

请求确定:

Request Headers - Accept-Encoding

响应不是-缺少Content-Encoding标头:Response Headers

这是我的Java代码:

@RequestMapping(value = "/download",
                method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> download(HttpServletRequest request, HttpServletResponse response) {
    log.debug("REST request to get the filesystem resource");

    // hardcoded for testing purpose
    File f = new File("C:/file.log.gz");
    InputStream inputStream = null;
    InputStreamResource inputStreamResource = null;
    HttpHeaders headers = null;
    try {
        inputStream = new FileInputStream(f);
        inputStreamResource = new InputStreamResource(inputStream);

        headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Content-Encoding", "gzip");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    return ResponseEntity
        .ok()
        .headers(headers)
        .contentType(MediaType.parseMediaType("text/plain"))
        .body(inputStreamResource);
}

Spring是否从响应中删除了这个特定的头?

java spring gzip httpresponse content-encoding
1个回答
1
投票

我刚刚发现它实际上在工作:)。我之前使用过BrowserSync对其进行测试,由于某种原因,它无法与BrowserSync一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.