如果文件不存在,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()));
你能给我一些建议如何解决这个问题吗
# 1 楼答案
只需选择一个不带
body
参数的ResponseEntity
构造函数来创建ResponseEntity
我将其更改为当图像不存在时返回404状态码,当图像存在时返回200状态码,这更符合HTTP状态码的语义