如果文件不存在,则返回空响应

时间:2019-08-24 07:20:59

标签: java spring spring-boot

我正在使用此代码从angular应用下载图像。

    @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);
    }

但是当我尝试下载未找到的映像时,我得到了正常的NPE。找不到图像文件时如何返回空响应?像这样:

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

您能给我一些如何解决此问题的建议吗?

1 个答案:

答案 0 :(得分:3)

只需选择一个没有ResponseEntity参数的body构造函数即可创建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);
    }

当图像不存在时,我将其更改为返回404状态代码,而当图像存在时,将其返回200,以更好地与HTTP状态码的语义对齐。