user13901284
user13901284

Reputation: 11

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 ??

Upvotes: 1

Views: 9787

Answers (1)

silentsudo
silentsudo

Reputation: 6963

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

Upvotes: 5

Related Questions