java - 如果文件不存在则返回空响应
问题描述
我正在使用此代码从 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()));
你能给我一些建议如何解决这个问题吗?
解决方案
只需选择一个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 的语义含义。
推荐阅读
- javascript - JS:XMLHtttpRequest 发送数据不起作用
- python - 使用 matplotlib 将轮廓图旋转 90 度
- c - 返回代码顶部/重置代码
- python - 如何从图像中删除背景
- amazon-web-services - 在 Docker 容器中设置 AWS RDS 持久层
- sql-server - 使用 [text()] 别名在 XML 查询中修剪逗号结尾
- java - 如何替换数据提供者的硬编码值
- javascript - JavaScript if 语句 PHP 调用
- python - 如何从 json 文件中获取嵌套键值
- javascript - Google 图表:无法读取 null 的属性“颜色”