问题
在进行文件下载的时候,一般都需要配置对应文件的Content-Type响应头。
Java
Path rootLocation = Paths.get("rootPath");
Path path = rootLocation.resolve("filename.png");
// 获取文件的Content-Type
String mimeType = Files.probeContentType(path);
org.springframework.core.io.Resource resource = new UrlResource(path.toUri());
return ResponseEntity.ok()
// 设置Content-Type响应头
.header(HttpHeaders.CONTENT_TYPE, mimeType)
.header(HttpHeaders.CONTENT_DISPOSITION, mimeType.startsWith("image/") ? "inline;filename*=utf-8''" + newFileName : "attachment;filename*=utf-8''" + newFileName)
.body(resource);
在Java中,当处理文件下载时,关键步骤包括确定文件的Content-Type(如通过Files.probeContentType方法)并设置HTTP响应头,如Content-Type和Content-Disposition。对于图片,可能设置为inline以在浏览器中直接显示,否则设为attachment以下载。SpringMVC的Resource和ResponseEntity用于构建响应。
9521

被折叠的 条评论
为什么被折叠?



