简体   繁体   中英

How to send image as response in Spring boot?

I am a beginner with spring boot (restController) and angular I want to send an image to my client(angular) with this method:

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

But the URL returns me a code 500 with this error

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

Can you help me, please??

As per the exception you have posted, it looks like the image path you trying to read is not found.

Also there are few corrections to the method, here is how i have done this:

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);

    }

Please make sure that the URI to Paths.get(...) is a valid otherwise you will still get java.nio.file.NoSuchFileException

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM