簡體   English   中英

如何在 Spring 引導中發送圖像作為響應?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM