Scala Play 2.0.2 download multiple files

I am new to Play and scala. My requirement is to provide a browse button in which we can select multiple files and download these files. Here is the code I wrote:

in 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 can not upload multiple files. Any idea what the problem is?

+5
source share
2 answers

First of all you do not need

="multiple"

It works equivalently

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


To upload to multiple files, there must be an attribute when defining the form
enctype="multipart/form-data"

For example, if you use helpers

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

or if you are not

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

In your controller, you want to try something like this (for Java, I'm sure it looks like 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 them to iterate through FilePart objects

Hope this looks like scala

+3

, :

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")

}
+1

All Articles