Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve uploaded files in Play!2 using Scala?

I'm trying to allow users to upload photos to the server and then view them. Uploading happens as described in this guide. Here is the code:

def upload = Action(parse.multipartFormData) { request =>
  request.body.file("picture").map { picture =>
    import java.io.File
    val filename = picture.filename 
    val contentType = picture.contentType
    picture.ref.moveTo(new File("/tmp/picture"))
    Ok("File uploaded")
  }.getOrElse {
    Redirect(routes.Application.index).flashing(
      "error" -> "Missing file"
    )
  }
}

It is unclear to me how to serve the uploaded images back to users that want to see them. Right now I am hosting the server on my own machine, so the code snippet from the guide writes the files to my D: drive, which isn't (and shouldn't be) available from the Internet. As far as I can see there are 2 options:

  1. Store the photos under the /public folder in my project (the one that is dedicated to assets). See here: http://www.playframework.org/documentation/2.0/Assets

  2. Write my own controller that servs images form custom locations from my drive.

For 1, I'm not sure if that is the purpose of assets. For 2, I have no idea how to write such a controller.

like image 240
Henry Henrinson Avatar asked Jul 12 '12 11:07

Henry Henrinson


2 Answers

The simple example is

def index = Action {
  Ok.sendFile(new java.io.File("/tmp/fileToServe.pdf"))
}

there is "Serving files" section at https://www.playframework.com/documentation/2.4.x/ScalaStream#Serving-files which explains how to serve files

like image 150
Eugene Platonov Avatar answered Nov 19 '22 18:11

Eugene Platonov


2.0.3 will feature an external Assets controller which might be (mis)used for this. Writing such a controller is no magic though, you have predefined folder where all your uploads are saved, and that's where you read them from. In the database you save the (unique) file name.

A different approach would be to save the uploaded files in the database. We do this with GridFS in MongoDB. A custom controller serves them back to the user. This way your data is stored in one central place, which also makes backups and recoveries simpler.

like image 33
Marius Soutier Avatar answered Nov 19 '22 16:11

Marius Soutier