首页 > 解决方案 > 如何将上传的文件复制到公用文件夹中?

问题描述

请看下面的代码:

def saveFile = Action(parse.multipartFormData) { request =>
  request.body.file("theFile") match {
    case Some(file) =>
      val filename = Paths.get(file.filename).getFileName
      file.ref.copyTo(Paths.get("PATH_TO_PUBLIC_FOLDER" + filename), replace = true)
      Ok("Done")

    case _ =>
      BadRequest("Error with file")
  }
}

如何获取公共文件夹的路径,以便复制上传的文件?

标签: scalafile-uploadplayframework

解决方案


我从这里得到了一个解决方案https://stackoverflow.com/a/47778722/2814580

import controllers.AssetsFinder
import play.api.Environment

// After injecting in the controller:
// @Inject()(af: AssetsFinder,env: Environment)

def saveFile = Action(parse.multipartFormData) { request =>
  request.body.file("theFile") match {
    case Some(file) =>
      val baseDir = env.rootPath + af.assetsBasePath + "/"
      val filename = Paths.get(file.filename).getFileName
      file.ref.copyTo(Paths.get(baseDir + filename), replace = true)
      Ok("Done")

    case _ =>
      BadRequest("Error with file")
  }
}

推荐阅读