.zip 文件下载为 f.txt 文件 - springboot

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

下面的代码始终下载

f.txt
文件,而不是在没有实际文件名和扩展名的情况下下载(此处为 .zip 扩展名)。

@RequestMapping(value = "/files/{fileId}", method = RequestMethod.GET, produces = "application/zip")
    public ResponseEntity<Resource> downloadFile(@PathVariable("fileId") String fileName) {
        log.info("Downloading file..!!!!");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/zip"));
        log.info("Content info : "+headers.getContentType().toString());
        File file = FileUtils.getFile("backup/" + fileName + ".zip");
        log.info("File name is : "+file.getName());
        FileSystemResource fileSystemResource = new FileSystemResource(file);

        return new ResponseEntity<>(fileSystemResource, headers, HttpStatus.OK);
    }

如果有人能让我知道错误在哪里/需要进行一些修改,那就太好了?

java spring-boot download
3个回答
12
投票

f.txt
来自
Content-Disposition
响应标头。这是修复 cve-2015-5211(RFD 攻击)

的结果

4
投票

要解决此问题,请添加

content-disposition
content-length
标头:

...
log.info("File name is : "+file.getName());

// Adding the following two lines should fix the download for you:
headers.set("content-disposition", "inline; filename=\"" + file.getName() + "\"");
headers.set("content-length", String.valueOf(file.length()));

FileSystemResource fileSystemResource = new FileSystemResource(file);
...

0
投票

我在接收PDF文件时也遇到了类似的问题。
您还可以使用以下解决方案来解决此问题:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.mediaType("pdf", MediaType.APPLICATION_PDF);
    }
}

或者更简单(如果您使用的是 Spring Boot)。
使用

application.yaml
文件注册类型:

spring:
  mvc:
    contentnegotiation:
      media-types:
        pdf: application/pdf

查看更多信息这里这里
我希望这个答案对某人有用。
祝你好运!

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