那么java后台springboot如何正确设置Content-Disposition头部信息
时间: 2023-06-05 15:09:03 浏览: 722
对于该问题,我可以给出以下回答:
在SpringBoot中,我们可以使用ResponseEntity类来设置Content-Disposition的头部信息。具体代码如下:
```
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile() {
// 从服务器中读取文件
Resource resource = fileStorageService.loadFileAsResource(fileName);
// 设置 Content-Disposition头部信息
String contentType = null;
try {
contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
} catch (IOException ex) {
logger.info("Could not determine file type.");
}
if(contentType == null) {
contentType = "application/octet-stream";
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType(contentType));
headers.setContentDisposition(ContentDisposition.builder("attachment").filename(resource.getFilename()).build());
return ResponseEntity.ok().headers(headers).body(resource);
}
```
其中,ContentDisposition.builder("attachment").filename(resource.getFilename()).build()可以设置附件的文件名。如果不需要设置附件名,可以只调用ContentDisposition.builder("attachment").build()。
希望以上回答能够帮助到您。