java - 下载时更改了少数内容类型的文件扩展名
问题描述
我现在正在使用下面的方法从服务器下载文件,对于一些扩展名为(“.png”、“.txt”、“.pdf”)的文件,文件正在正确下载,但对于(“.exe”)来说文件正在下载为 f.txt 我可以知道这段代码有什么问题。对于 .exe 文件,内容正在写入“f.txt”文件。我也在使用Files.probeContentType(file.toPath()); 确定媒体类型并将其设置在响应实体的内容类型中。提前致谢!:)。扩展名更改的媒体类型为application/x-msdownload
public ResponseEntity<InputStreamResource> getFileFromDisk(String filename) throws IOException {
ResponseEntity<InputStreamResource> filedata = null;
String file_path = "/e:/filesfolder/" + filename;
String fileType = "Undetermined";
final File file = new File(file_path);
fileType = Files.probeContentType(file.toPath());
System.out.println(fileType);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file_path));
String file_checksum = checksumcalc.calculateChecksum(file_path);
filedata = ResponseEntity.ok().header("Md5", file_checksum)
.contentType(MediaType.parseMediaType(fileType)).body(resource);
return filedata;
}
解决方案
为避免此f.txt
问题,您必须定义Content-disposition
标题以指定附件的文件名。
例如 :
filedata = ResponseEntity.ok()
.header("Content-disposition", "attachment; filename=" + fileName)
.header("Md5", file_checksum)
.contentType(MediaType.parseMediaType(fileType)).body(resource);
推荐阅读
- json - 如何在 json 库(游戏框架)中呈现排序地图?
- ios - 将应用程序上传到 iTunes Connect 时出现问题
- android - 获取是否在 android 6 中启用了后台数据限制的代码
- python - 如何为方法响应制作类型提示,其中响应取决于python中的方法参数?
- cmake - 通过 Cmake 外部项目传递依赖
- excel - VBA - 获取工作表中值的行号,然后将不同的值插入同一行的不同列
- .net-core - NuGet 的 npm 版本模拟
- java - Java swing 重用监听器
- javascript - Puppeteer Web Scraper 返回空数据
- javascript - 如何在 Angular 模板中设置多个道具?