2016-12-28 115 views
1

下面的代碼總是下載一個f.txt文件,而不下載實際的文件名和擴展名(這裏是.zip擴展名)。.zip文件作爲f.txt文件下載 - springboot

@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); 
    } 

如果有人能讓我知道錯誤在哪裏/要做些修改,那將會很棒。

回答

5

f.txt來自Content-Disposition響應標頭。這是固定的結果cve-2015-5211(RFD攻擊)

+4

因此,使用'headers.setContentDispositionFormData( 「附件」, 「my.zip」) ;'或者這樣。 –

1

要解決此問題,添加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); 
...