首页 > 解决方案 > 下载时更改了少数内容类型的文件扩展名

问题描述

我现在正在使用下面的方法从服务器下载文件,对于一些扩展名为(“.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;
        }

标签: javaspringspring-mvcspring-boot

解决方案


为避免此f.txt问题,您必须定义Content-disposition标题以指定附件的文件名。

例如 :

filedata = ResponseEntity.ok()
    .header("Content-disposition", "attachment; filename=" + fileName)
    .header("Md5", file_checksum)
    .contentType(MediaType.parseMediaType(fileType)).body(resource);

推荐阅读