玩!上传文件并保存到AWS S3 [英] Play! Upload file and save to AWS S3

查看:272
本文介绍了玩!上传文件并保存到AWS S3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Play 2.3,并且希望将上传的文件存储到S3,所以我使用Play-S3模块.

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

但是,我陷入了困境,因为我需要创建一个BucketFile并使用此模块上传到S3,然后使用文件内存中的Array [Byte]创建一个BucketFile.表演!正文解析器为我提供了光盘文件上的临时文件.如何将该文件放入BucketFile?

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?

这是我的控制器操作:

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

此代码不起作用,因为file.ref.file.toString()并没有真正返回文件的字符串表示形式.

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

推荐答案

导入以下内容:

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

要创建Array [Byte],请执行以下操作:

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)

这篇关于玩!上传文件并保存到AWS S3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆