英文:
Spring Return error format in ResponseEntity
问题
我尝试使用ResponseEntity来返回byte[]对象
return new ResponseEntity<byte[]>(new Response(ResultCode.SUCCESS, SUCCESS).setResult(dataObj), HttpStatus.OK);
但是我得到了这样的响应:
[![enter image description here][1]][1]
另一种方式是我尝试直接返回byte[]对象
return dataObj;
响应如下:
[![enter image description here][2]][2]
为什么会有不同?我能否像第二张图片那样返回带有数据的ResponseEntity?
英文:
I try to return the byte[] object by using ResponseEntity
return new ResponseEntity<>(new Response(ResultCode.SUCCESS, SUCCESS).setResult(dataObj), HttpStatus.OK);
but and got a response like that:
and another way I try to return the direct byte[] object
return dataObj;
Why do we have different? and Can I return the ResponseEntity with data like the 2nd image?
答案1
得分: 0
尝试以下代码。访问此API时,它将以响应的方式发送图像本身。
@GetMapping(value = "/image/{id}")
public ResponseEntity<?> getImageById(@PathParam Long id) throws Exception {
String imageData = this.entityRepository.findById(id).orElse(null).getData();
byte[] imageByte = Base64.getDecoder().decode(new String(imageData).getBytes("UTF-8"));
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
return new ResponseEntity<>(imageByte, headers, HttpStatus.OK);
}
英文:
Try following code. It will send image itself in response on accessing this API.
@GetMapping(value = "/image/{id}")
public ResponseEntity<?> getImageById(@PathParam Long id) throws Exception {
String imageData = this.entityRepository.findById(id).orElse(null).getData();
byte[] imageByte = Base64.getDecoder().decode(new String(imageData).getBytes("UTF-8"));
MediaType mediaType = MediaType.APPLICATION_OCTET_STREAM;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(mediaType);
return new ResponseEntity<>(imageByte, headers, HttpStatus.OK);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论