Java 如何在Spring boot中将映像作为响应发送?
我是spring boot(restController)和angular的初学者,我想用以下方法向我的客户机(angular)发送一个图像:Java 如何在Spring boot中将映像作为响应发送?,java,spring,spring-boot,spring-restcontroller,Java,Spring,Spring Boot,Spring Restcontroller,我是spring boot(restController)和angular的初学者,我想用以下方法向我的客户机(angular)发送一个图像: @RestController public class ProductRestController { @Autowired private ProductRepository pr; @GetMapping (path = "/ photoProduit / {id}", produces = org.sprin
@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
您能帮我吗???根据您发布的异常,您试图读取的图像路径似乎找不到 该方法也有一些修正,以下是我是如何做到这一点的:
导入org.springframework.core.io.ByteArrayResource;
导入org.springframework.core.io.Resource;
@GetMapping(value=“/image”,products=MediaType.image\u JPEG\u值)
public ResponseEntity image()引发IOException{
final ByteArrayResource inputStream=新建ByteArrayResource(Files.readAllBytes(path.get(
“/home/silentsudo/Videos/dum1111b.jpg”
)));
返回响应性
.status(HttpStatus.OK)
.contentLength(inputStream.contentLength())
.主体(输入流);
}
请确保
path.get(…)
的URI有效,否则您仍将获得java.nio.file.NoSuchFileException
根据您发布的异常,似乎找不到您尝试读取的图像路径
该方法也有一些修正,以下是我是如何做到这一点的:
导入org.springframework.core.io.ByteArrayResource;
导入org.springframework.core.io.Resource;
@GetMapping(value=“/image”,products=MediaType.image\u JPEG\u值)
public ResponseEntity image()引发IOException{
final ByteArrayResource inputStream=新建ByteArrayResource(Files.readAllBytes(path.get(
“/home/silentsudo/Videos/dum1111b.jpg”
)));
返回响应性
.status(HttpStatus.OK)
.contentLength(inputStream.contentLength())
.主体(输入流);
}
请确保
path.get(…)
的URI有效,否则您仍将获得java.nio.file.NoSuchFileException
我相信他找不到图像。因此,要么这个unknow.png图像不存在,要么为unknown.png图像指定的路径不正确。我相信他找不到该图像。因此,要么此unknow.png图像不存在,要么为unknown.png图像指定的路径不正确。回答正确,thx回答正确,thx