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?
First of all you do not need
="multiple"
This works equivalently
<input type="file" name="files" multiple id="files" size="30">
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
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With