[英]How to send image as response in Spring boot?
I am a beginner with spring boot (restController) and angular I want to send an image to my client(angular) with this method:我是 spring 引导(restController)和 angular 的初学者我想用这种方法向我的客户(角度)发送图像:
@RestController public class ProductRestController {
@Autowired private ProductRepository pr;
@GetMapping (path = "/ photoProduit / {id}", produces = org.springframework.http.MediaType.IMAGE_PNG_VALUE)
public byte [] getPhoto (@PathVariable Long id) throws IOException {
Product p = pr.findById (id) .get (); return Files.readAllBytes (Paths.get (System.getProperty ("user.home") + "/ ecom / produits /" + p.getPhotoName ()));
}
}
But the URL returns me a code 500 with this error但是 URL 返回一个代码500并出现此错误
There was an unexpected error
(type = Internal Server Error, status = 500). C: \ Users \ Gonan \ ecom \ products \ unknow.png java.nio.file.NoSuchFileException: C: \ Users \ Gonan \ ecom \ produits \ unknow.png
Can you help me, please??你能帮我吗??
As per the exception you have posted, it looks like the image path you trying to read is not found.根据您发布的异常,看起来您尝试读取的图像路径未找到。
Also there are few corrections to the method, here is how i have done this:该方法也有一些更正,这是我的做法:
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
@GetMapping(value = "/image", produces = MediaType.IMAGE_JPEG_VALUE)
public ResponseEntity<Resource> image() throws IOException {
final ByteArrayResource inputStream = new ByteArrayResource(Files.readAllBytes(Paths.get(
"/home/silentsudo/Videos/dum111111b.jpg"
)));
return ResponseEntity
.status(HttpStatus.OK)
.contentLength(inputStream.contentLength())
.body(inputStream);
}
Please make sure that the URI to Paths.get(...)
is a valid otherwise you will still get java.nio.file.NoSuchFileException
请确保
Paths.get(...)
的 URI 有效,否则您仍然会收到java.nio.file.NoSuchFileException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.