Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Play 2.0.2 multiple file upload

I am new to Play and scala. My requirement is to provide a browse button where we can select multiple files and upload those files. Here is code I have written:

in the scala.html file:

<input type="file" name="files" multiple="multiple" id="files" size="30">

in the Controller:

def upload = Action(parse.multipartFormData) { request =>
  request.body.file("files").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"
    )
  }
}

But I am not able to upload multiple files. Any idea what is the issue here?

like image 580
Prateek Avatar asked Sep 06 '12 23:09

Prateek


2 Answers

First of all you do not need

="multiple"

This works equivalently

<input type="file" name="files" multiple id="files" size="30">


To load in multiple files, when defining your form must have the attribute
enctype="multipart/form-data"

For example, if using the helpers

@helper.form(action = routes.MyController.submit(), 'enctype -> "multipart/form-data", 'id -> "myform")

or if you're not

<form action=... enctype="multipart/form-data" id="myform">

In your controller you want to try something like this (for Java, I'm sure its similar in Scala)

//Get all files bound to the form when submitted 
List<FilePart> plate_files = request().body().asMultipartFormData().getFiles();
//Get files from a specific name or id
FilePart myfile = request().body().asMultipartFormData().getFile("files");

Then you can use these the iterate through the FilePart objects

Hopefully its similar in scala

Cheers

like image 140
Omar Wagih Avatar answered Oct 26 '22 19:10

Omar Wagih


You can try like this as well if you like:

def uploadFiles: Action[AnyContent] { request =>
  val files: Option[Seq[FilePart[TemporaryFile]]] = request.body.asMultipartFormData.map(_.files)
   val filesJavaIO: Option[Seq[File]] = files map { fileSeq => fileSeq map { file =>
    file.ref.moveTo(new File("/tmp/myFiles"))
  }
  }
Ok("File uploaded")

}
like image 22
Arpit Suthar Avatar answered Oct 26 '22 19:10

Arpit Suthar