Reputation: 401
I am trying to write a simple file upload application, that would upload a file to a server, but when I run the code, a get a type mismatch error. I got the code from the play framework documentation, click here The error occurs around here:
picture.ref.moveTo(Paths.get(s"/tmp/picture/$filename"), replace = true)
The error around there says something like this:
Type mismatch, expected: File, actual: Path
My full code is below
def uploader = Action(parse.multipartFormData) { implicit request =>
request.body.file("picture").map { picture =>
val filename = Paths.get(picture.filename).getFileName
picture.ref.moveTo(Paths.get(s"/tmp/picture/$filename"), replace = true)
Ok("File uploaded")
}.getOrElse {
Redirect(routes.FileUploadController.index).flashing(
"error" -> "Missing file")
}
}
Upvotes: 0
Views: 1069
Reputation:
Try something like this:
import java.io.File
import java.nio.file.attribute.PosixFilePermission._
//If you need authenticating, simply use silhouette for ACL, otherwise replace this line
def uploadPhoto = silhouette.SecuredAction.async(parse.multipartFormData) { implicit request =>
Future {
request.body
.file("photo")
.map { photo =>
val fileName = UUID.randomUUID.toString
val pathToStorage = "default"
val file = new File(s"$pathToStorage/$fileName.jpg")
photo.ref.moveTo(file)
val attr = util.EnumSet.of(OWNER_READ, OTHERS_READ, GROUP_READ)
Files.setPosixFilePermissions(file.toPath, attr)
Ok(s"$fileName.jpg")
}
.getOrElse {
BadRequest("Missing file")
}
}
}
If you want to simply upload a file from disk, just replace file
variable to the next line:
val file = Paths.get(s"/path/to/picture.jpg").toFile
Also, it's a good practice to specify file parameters for read/write/execute
modes, I've provided the example with permissions above.
Upvotes: 1