Search code examples
javaspringspring-bootget

Spring boot download file with InputStreamResource case when file does not exist


I have a working method to download a file using Spring Boot using InputStreamResource object.

Sometimes I have a case where the file to download does not exist, in this case when the file download is over I get all java exceptions written in it.

My question is how to proceed in this case to deny user file download, and have a response with 'file does not exist'?

I thought about throwing a exception but the user would not get the info without checking the logs

here's the code:

@GetMapping("/downloadfile")
public ResponseEntity<InputStreamResource> getFile(@RequestParam(value = "filePath") String filePath) throws FileNotFoundException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {

        File file = new File(filePath);
        if (!file.exists()) {
            // What should I do there?
            //throw new CustomizeException("Could not find the file"); ?
        }
        MediaType mediaType = MediaTypeUtils.getMediaTypeForFileName(this.servletContext, file);
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .contentType(mediaType).contentLength(file.length()).body(resource);
    }

Solution

  • You can return a 404 (not found).

        if (!file.exists()) {
           return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
    

    You will not need to check logs or throws an exception because is already a talking status