[英]How to send image as response in Spring boot?
我是 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 ()));
}
}
但是 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
你能帮我吗??
根据您发布的异常,看起来您尝试读取的图像路径未找到。
该方法也有一些更正,这是我的做法:
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);
}
请确保Paths.get(...)
的 URI 有效,否则您仍然会收到java.nio.file.NoSuchFileException
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.