1 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.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 ()));
}
}
Run Code Online (Sandbox Code Playgroud)
但 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
Run Code Online (Sandbox Code Playgroud)
你能帮我吗 ??
根据您发布的异常,看起来您尝试读取的图像路径未找到。
该方法也有一些修正,以下是我的做法:
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);
}
Run Code Online (Sandbox Code Playgroud)
请确保 URI 有效Paths.get(...),否则您仍会收到java.nio.file.NoSuchFileException
| 归档时间: |
|
| 查看次数: |
8396 次 |
| 最近记录: |