Peter Penzov
Peter Penzov

Reputation: 1680

Return empty response if file is not present

I'm using this code to download a image from angular app.

    @RequestMapping("/files/{merchant_id}")
    public ResponseEntity<byte[]> downloadLogo(@PathVariable("merchant_id") Integer merchant_id) throws IOException {
        File file = new File(UPLOADED_FOLDER, merchant_id.toString() + "/merchant_logo.png");
        InputStream in = FileUtils.openInputStream(file);

        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);

        return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED);
    }

But when I try to download a image which is not found I get NPE which is normal. How I can return empty response when the image file is not found? Something like:

return ResponseEntity.ok(...).orElse(file.builder().build()));

Can you give me some advice how to fix this?

Upvotes: 1

Views: 916

Answers (1)

Ken Chan
Ken Chan

Reputation: 90497

Just choose a ResponseEntity constructor that is without body argument to create ResponseEntity

    File file = new File(UPLOADED_FOLDER, merchant_id.toString() + "/merchant_logo.png");
    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_PNG);

    if (!file.exists()) {
        return new ResponseEntity<byte[]>(headers,HttpStatus.NOT_FOUND);
    }else{
        InputStream in = FileUtils.openInputStream(file);
        return new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.OK);
    }

I change it to return 404 status code when the images does not exist and 200 when the images exist which better align with HTTP status code 's semantic meaning.

Upvotes: 3

Related Questions