amir rad
amir rad

Reputation: 122

get content file in java

I used this method to download and get content type

    @GetMapping("/downloadFile/")
    public ResponseEntity<Resource> downloadFile(@RequestParam String fileName, HttpServletRequest request) {
        // Load file as Resource
        Resource resource = fileStorageService.loadOneFileAsResource(fileName);

        // Try to determine file's content type
        String contentType = null;
        try {
            contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
        } catch (IOException ex) {
            logger.info("Could not determine file type.");
        }

        // Fallback to the default content type if type could not be determined
        if(contentType == null) {
            contentType = "application/octet-stream";
        }

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

But always detect my content "application/octet-stream", what is problem and what should I do? thanks in advance.

Upvotes: 1

Views: 1030

Answers (1)

Pritam Banerjee
Pritam Banerjee

Reputation: 18923

You can download the file, save it and then use the following:

Path path = Paths.get(resource.getURI());
String contentType = Files.probeContentType(path);

This should give you the content type. Look over here.

Upvotes: 1

Related Questions