Search code examples
javaspringspring-mvcspring-boot

File Extension getting changed for few content types when downloaded


I am using the below method to download the file from server now for few files with extensions (".png",".txt",".pdf") the files are downloading correctly but where as for (".exe") the file is downloading as f.txt may i know what's wrong with this code.For .exe files the content is being written to a "f.txt" file . I am also usoing Files.probeContentType(file.toPath()); to determine the media type and setting it in content type of respnse entity.Thanks in advance! :). the media type where extension changing is 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;
        }

Solution

  • To avoid the f.txt issue, you have to define the Content-disposition header to specify the filename of the attachment.

    For example :

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