user2975535 user2975535 - 27 days ago 20
Scala Question

Play Framework 2.5.9 Scala handling multipart/form-data file field allways Some

I'm following documentation from here https://www.playframework.com/documentation/2.5.x/ScalaFileUpload to handle file upload in form.
My code is here:

def add(method: String) = Action(parse.multipartFormData) { implicit request =>
if (method == "GET") {
Ok(views.html.add(uploadForm))
} else {
uploadForm.bindFromRequest().fold(
hasErrors => BadRequest(views.html.add(hasErrors)),
form => {
Logger.debug(request.body.file("myfilefield").toString)
Ok(views.html.add(uploadForm))
}
)
}
}


Whenever I submit this form, even if I didn't select file in file field I'm getting something like this in console:


[debug] application -
Some(FilePart(myfilefield,,Some(application/octet-stream),TemporaryFile(/var/folders/n3/8nrp7hw94bqbsjbcz00n5hk40000gn/T/playtemp4371116121043398878/multipartBody1548294152084205009asTemporaryFile)))


I can't understand why is this so. I think there are should be None in
request.body.file("myfilefield")
if I didn't select file before submitting form.
How can I find if file was submitted?

Ok. Now I just copied code from documentation and got the same result :(
Here is my controller action:

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(s"/tmp/picture/$filename"))
Ok("File uploaded")
}.getOrElse {
Redirect(routes.HomeController.uploadtest()).flashing(
"error" -> "Missing file")
}
}


and here is my view:


@()

@helper.form(action = routes.HomeController.upload, 'enctype -> "multipart/form-data") {

<input type="file" name="picture">

<p>
<input type="submit">
</p>

}



Whenever I submit this form I got "File uploaded" message.

Answer