Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java + Spring Boot : Downloading image and pass it to a request

I have a Spring Boot application which should act like a proxy.

It should process requests like "http://imageservice/picture/123456"

Then the application should generate a new request to "http://internal-picture-db/123456.jpg" where it should download the picture behind it (123456.jpg) and then pass it to the response and serve it.

It should be like...

@RequestMapping("/picture/{id}")
public String getArticleImage(@PathVariable String id, HttpServletResponse response) {

    logger.info("Requested picture >> " + id + " <<");

    // 1. download img from http://internal-picture-db/id.jpg ... 

    // 2. send img to response... ?!

    response.???

}

I hope it's clear what I mean...

So my question is: What is the best way to do so?

And just for information it is not possible to just send a redirect because the system is not available in the internet.

like image 203
DaUser Avatar asked Apr 22 '15 09:04

DaUser


1 Answers

I would use the response body to return the image and not a view for example:

@RequestMapping("/picture/{id}")
@ResponseBody
public HttpEntity<byte[]> getArticleImage(@PathVariable String id) {

    logger.info("Requested picture >> " + id + " <<");

    // 1. download img from http://internal-picture-db/id.jpg ... 
    byte[] image = ...

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.IMAGE_JPEG);
    headers.setContentLength(image.length);

    return new HttpEntity<byte[]>(image, headers);
}

You have a post which can help you to download the image from an other url: how to download image from any web page in java

like image 145
Steph Avatar answered Oct 06 '22 14:10

Steph