我有一个Springboot REST应用程序,可以从给定目录下载文件。 下载可以是任何文件文件,并且具有任何格式,我想使用原始文件名作为下载文件的文件名。
我使用下面的代码在标题中设置文件名,并将标题添加到响应中:
@RestController
@RequestMapping("/downloads")
public class DownloadCsontroller {
...
@GetMapping
public void downloadSingleFile(@RequestParam("file") String filename, HttpServletResponse response) throws IOException {
String filepath = m_attachmentPathLocation + File.separator + filename;
File file = new File(filepath);
String contentType = getContentType(file);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(contentType);
response.setHeader("Content-Disposition:", "attachment;filename=\"" + file.getName() + "\"");
...
}
...
}
使用setHeader()中的“Content-Disposition”和“Content-Disposition:”进行测试。
除PDF,ZIP,RAR,EXE等外,几乎所有内容都有效(文件类型)
列表中没有的任何文件(类型)都可以使用所需的文件名下载。 但是当任何文件下载(PDF,ZIP,RAR,EXE等)时......似乎它会像永远一样持续加载......我甚至看不到在POSTMAN,督察,萤火虫等发送的任何请求。
如果我发表评论:
//response.setHeader("Content-Disposition:", "attachment;filename=\"" + file.getName() + "\"");
它可以工作,但文件名将设置为请求映射的名称。在这种情况下是“下载”。
我见过很多使用“Content-Disposition”标题更改附件文件名的示例......但似乎它在这些文件类型上失败了。
我还没有任何配置,这有点奇怪,因为在我搜索的大多数样本中......这应该正在运行或正在运行。
TIA
答案 0 :(得分:0)
请添加@GetMapping(produce = MediaType.APPLICATION_OCTET_STREAM_VALUE)
而不是返回直接文件尝试返回流。
还要记下"内容 - 处置:"如果请求的应用IP&端口号与服务器应用IP&端口号。
答案 1 :(得分:0)
事情会起作用如果您可以通过使用org.springframework.http.HttpHeaders类设置所有标头值来稍微改变代码。 现在查看您的代码,我怀疑您尝试公开允许下载多部分文件的API。 我建议你不要使用HttpServletResponse类来设置Content- Dispositionheader,而是使用HttpHeaders类。以下是重新格式化的代码
@RestController
public class DownloadCsontroller {
@GetMapping(value="/downloads")
public ResponseEntity<Object> downloadSingleFile(@RequestParam("file")
String filename) throws IOException {
String filepath = m_attachmentPathLocation + File.separator + filename;
File file = new File(filepath);
String contentType = getContentType(file);
/* response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(contentType);
response.setHeader("Content-Disposition:", "attachment;filename=\""
+ file.getName() + "\"");
*/
// Here is the below Code you need to reform for Content-
//Disposition and the remaining header values too.
HttpHeaders headers= new HttpHeaders();
headers.add("Content-Disposition", "attachment; filename
=whatever.pdf");
headers.add("Content-Type",contentType);
// you shall add the body too in the ResponseEntity Return object
return new ResponseEntity<Object>(headers, HttpStatus.OK);
}
}