Pass data to filePartHandler of PlayBodyParsers.multipartFormData

From https://www.playframework.com/documentation/2.6.x/ScalaFileUpload#Writing-your-own-body-parser

type FilePartHandler[A] = FileInfo => Accumulator[ByteString, FilePart[A]]

def handleFilePartAsFile: FilePartHandler[File] = {
  case FileInfo(partName, filename, contentType) =>
    val perms = java.util.EnumSet.of(OWNER_READ, OWNER_WRITE)
    val attr = PosixFilePermissions.asFileAttribute(perms)
    val path = JFiles.createTempFile("multipartBody", "tempFile", attr)
    val file = path.toFile
    val fileSink = FileIO.toPath(path)
    val accumulator = Accumulator(fileSink)
    accumulator.map { case IOResult(count, status) =>
      FilePart(partName, filename, contentType, file)
    }(ec)
}

def uploadCustom = Action(parse.multipartFormData(handleFilePartAsFile)) { request =>
  val fileOption = request.body.file("name").map {
    case FilePart(key, filename, contentType, file) =>
      file.toPath
  }

  Ok(s"File uploaded: $fileOption")
}

Is there a way to get some request data into handleFilePartAsFile? If I could get a bucket param in there, then it seems I could stream right to online blob storage. Or is there a better way?

Hi @jibbers42,

This would be just regular Scala code, so you can pass the bucket name as a parameter to handleFilePartAsFile, for example:

def handleFilePartAsFile(bucket: String): FilePartHandler[File] = {
    ...
}

And then, in your actions:

def uploadCustom = Action(parse.multipartFormData(handleFilePartAsFile("my-bucket"))) { request =>
    ...
}

Best.

haha, I’m not sure why it was in my head I couldn’t change the signature of handleFilePartAsFile.

Thanks!