简体   繁体   中英

Play! Upload file and save to AWS S3

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM