如何在播放中进行文件上传(Scala)

时间:2018-06-20 05:31:08

标签: scala file-upload playframework

我正在尝试编写一个简单的文件上传应用程序,该应用程序会将文件上传到服务器,但是当我运行代码时,出现类型不匹配错误。我从播放框架文档中获取了代码,请点击here,此错误发生在这里:

picture.ref.moveTo(Paths.get(s"/tmp/picture/$filename"), replace = true)

那里的错误说像这样:

Type mismatch, expected: File, actual: Path

我的完整代码在下面

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

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

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

如果您只想从磁盘上传文件,只需将file变量替换为下一行:

val file = Paths.get(s"/path/to/picture.jpg").toFile

此外,为read/write/execute模式指定文件参数也是一种好习惯,我已经为示例提供了以上权限。