3

I tried to return the image as shown below:

return ok(new File("http://example.com/dpa/client_name/images/client_log.jpg"));

but the method in the controller couldn't fetch the image from the remote server and threw a image not found exception.

How do I retrieve an image from the remote server and return as a response using java play framework?

Swapnil B.
  • 729
  • 1
  • 8
  • 23
  • Why would you not directly redirect the browser to the image on the remote server? – gpgekko Feb 06 '17 at 13:44
  • I have to return the image to a client request in his website's iframe. – Swapnil B. Feb 07 '17 at 06:21
  • as per Benchik's answer here: http://stackoverflow.com/a/20838010/2129212 He is reading the file from the local public folder. I want to read it from the web(remote path) and then return it from the function fetching it. – Swapnil B. Feb 07 '17 at 06:48

1 Answers1

9

Simply use WS API

package controllers;

import play.libs.ws.WSClient;
import play.mvc.Controller;
import play.mvc.Result;

import java.util.concurrent.CompletionStage;
import javax.inject.Inject;


public class HomeController extends Controller {

    @Inject WSClient ws;

    public CompletionStage<Result> index() {
        return ws
          .url("http://www.maine-coon-cat-nation.com/image-files/orange-maine-coon-cat.jpg")
          .get()
          .thenApply(file -> ok(file.getBodyAsStream()).as("image/jpeg"));
    }

}
Andriy Kuba
  • 8,093
  • 2
  • 29
  • 46
  • thanks a million for your answer. How do I use CompletionStage further? I want to send data to the intended user through JSON. – Swapnil B. Feb 07 '17 at 11:13
  • `public CompletionStage index()` is the "ouput point", you need to "bind" it to the url in the `conf\routes` file, like `GET / controllers.HomeController.index`. You can read how to serve JSON responses in the documentation "https://www.playframework.com/documentation/2.5.x/JavaJsonActions#serving-a-json-response" I am not sure that send image through JSON is a good idea, you will need to code it's somehow, like base64 or so – Andriy Kuba Feb 07 '17 at 13:12