如何在Spring Boot中发送图像作为响应?

时间:2020-07-09 23:48:37

标签: java spring spring-boot spring-restcontroller

我是Spring Boot(restController)和angular的初学者,我想使用此方法将图像发送到我的客户端(angular):

<body> 
    <input id="searchbar" onkeyup="search_topics()" type="text"
        name="search" placeholder="Search topics...."> 
</body>

<div class=" overlay-image _b1 ">
  <a href="url for block">
    <img class=" image _b2 " src="https://i.redd.it/m3u40szpez231.jpg" />
    <div class=" normal _b4 ">
      <div class="text">Title of a block</div>
    </div>
    <div class=" hover _b3 ">
      <div class=" text_2 ">Test that appears when block is hovered</div>
    </div>
  </a>
</div>

<div class=" overlay-image _b1 ">
  <a href="url for block">
    <img class=" image _b2 " src="https://i.redd.it/m3u40szpez231.jpg" />
    <div class=" normal _b4 ">
      <div class="text">Title of a block 2</div>
    </div>
    <div class=" hover _b3 ">
      <div class=" text_2 ">Test that appears when block is hovered</div>
    </div>
  </a>
</div>

但是该网址返回了错误代码 500

@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 ()));
        
    }
 }

请问您能帮我吗??

1 个答案:

答案 0 :(得分:1)

根据您发布的例外情况,看起来好像找不到您尝试读取的图像路径。

该方法也有一些更正,这就是我的方法:

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