score:0

Accepted answer

Ah, We need to use Streaming HTTP responses to do this.

Here is the documentation.... https://www.playframework.com/documentation/2.6.x/ScalaStream

my controller code will be

 package controllers

import akka.stream.scaladsl.{FileIO, Source}
import akka.util.ByteString
import javax.inject.{Inject, Singleton}
import play.api.http.HttpEntity
import play.api.mvc._



@Singleton
class ImageServerController @Inject()(cc: ControllerComponents)(implicit assetsFinder: AssetsFinder)
  extends AbstractController(cc) {



  def serveImages(imageName:String):Action[AnyContent] = Action {

    val file = new java.io.File("/tmp/images/"+imageName)
    val path: java.nio.file.Path = file.toPath
    val source: Source[ByteString, _] = FileIO.fromPath(path)

    Result(
      header = ResponseHeader(200, Map.empty),
      body = HttpEntity.Streamed(source, None, Some("image/jpeg"))
    )
  }


}

score:1

Here are two options :

1) After the upload of the file, you move it to a folder (for example /uploads) created in your app directory. Then you serve these images via Apache which is more adapted than play to serve assets.

You need to have Apache as a reverse proxy of your application and configure a url to serve assets instead or redirecting to your application.

2) You also move the file to a folder (/uploads) and then you create a route in you application

GET /img/:name controllers.MyController.serveImage(name: String)

and in your controller :

public Result serveImage(String name) {
    String path = "uploads/" + name;
    return ok(new File(path));
}

The benefit of 2) is that you can manage authorisations when serving the file depending on the user.


Related Query

More Query from same tag