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

时间:2016-12-28 15:09:56

标签: java spring-boot download

下面的代码总是下载一个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);
    }

如果有人能让我知道错误在哪里/需要做些修改,那会很棒吗?

2 个答案:

答案 0 :(得分:7)

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

的结果

答案 1 :(得分:4)

要解决此问题,请添加content-dispositioncontent-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);
...