如何将上传的文件复制到公用文件夹?

问题描述 投票:0回答:1

请参见下面的代码:

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

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

scala file-upload playframework
1个回答
0
投票

我从这里获得了一个解决方案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")
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.