首页 > 解决方案 > 如果文件不存在则返回空响应

问题描述

我正在使用此代码从 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()));

你能给我一些建议如何解决这个问题吗?

标签: javaspringspring-boot

解决方案


只需选择一个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 status code 的语义含义。


推荐阅读