我有一个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() + """);
...
}
...
}
使用" content-disposition"one_answers" content-disposition:''setheader((。
进行了测试。几乎所有内容都有效(文件类型(,除了PDF,ZIP,RAR,EXE等
可以使用所需的文件名下载列表中的任何文件(类型(。但是,当任何文件下载(pdf,zip,rar,exe等(...看来它像永远一样连续加载...我什至看不到邮递员,检查员,firebug等中发送的任何请求。
如果我发表评论:
//response.setHeader("Content-Disposition:", "attachment;filename="" + file.getName() + """);
它可以工作,但是文件名将设置为请求映射的名称。在这种情况下是"下载"。
我看到了许多使用" content-disposition"标头更改附件文件名的样本...但是似乎在这些文件类型上失败了。
我还没有配置,这有点奇怪,因为在我搜索的大多数样本中...应该运行或工作。
tia
请添加@getMapping(praedes = mediatype.application_octet_stream_value(
,而不是返回直接文件尝试返回流。
还请注意,如果请求应用程序IP&端口号不同于服务器应用程序IP&端口号。
如果您可以使用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);
}
}