Play! Upload file and save to AWS S3

2020-06-21 11:36发布

问题:

I am using Play 2.3 and want to store the uploaded files to S3, so I use Play-S3 module.

However, I got stuck because I need to create a BucketFile to upload to S3 with this module, and a BucketFile is created using an Array[Byte] in memory of the file. The Play! body parser gives me a temporary on disc file. How can I put this file into BucketFile?

Here is my controller Action:

def upload = Action.async(parse.multipartFormData) { implicit request =>
    request.body.file("file").map{ file =>
      implicit val credential = AwsCredentials.fromConfiguration
      val bucket = S3("bucketName")
      val result = bucket + BucketFile(file.filename, file.contentType.get, file.ref.file.toString.getBytes)
      result.map{ unit =>
        Ok("File uploaded")
      }
    }.getOrElse {
      Future.successful {
        Redirect(routes.Application.index).flashing(
          "error" -> "Missing file"
        )
      }
    }
  }

This code does not work because file.ref.file.toString() does not really return the string representation of a file.

回答1:

Import the following:

import java.nio.file.{Paths, Files}

To create the Array[Byte] do:

val byteArray = Files.readAllBytes(Paths.get(file.ref.file.getPath))

Then upload with:

BucketFile(file.filename, file.contentType.get, byteArray, None, None)