4

我创建了一个 api 来向我发送文件,我会将它们上传到 S3,并且我使用akka-stream-alpakka-s3库来使用流来完成它。

我的问题是在我的控制器中我可以将文件转换为 Jave 文件:

  def uploadToS3() = Action(parse.multipartFormData) { request =>
    request.body.file("file").map { filePart =>
      val filename = Paths.get(filePart.filename).getFileName
      val file = Paths.get(s"/tmp/$filename").toFile // this is java file
      saveToS3(file, filename)
    }
    ...
  }

在我的 s3 服务函数中,我只能使用 scala 文件,因为它有一个“toByteArray”函数,我需要它作为源代码,它看起来像这样:

import scala.reflect.io.File

class S3Service @Inject()(mys3Client: S3Client,
                          configuration: Configuration,
                          implicit val executionContext: ExecutionContext,
                          implicit val actorSystem: ActorSystem) {

  implicit val materializer: ActorMaterializer = ActorMaterializer()
  val bucket: String = configuration.get[String]("my.aws.s3.bucket")

// func to save to s3
  def saveToS3(file: File, fileName: String): Future[AWSLocation] = {

// here im creating uuid so i to pass as directory so it will be possible to have files with the same name
    val fileNameUUID: String = s"${UUID.randomUUID()}-$fileName"
// this will be my sinc for the stream    
    val s3Sink: Sink[ByteString, Future[MultipartUploadResult]] = mys3Client.multipartUpload(s"$bucket/$fileNameUUID", fileName)

// here is my issue: i need to transform the file to bytstring so I can creat it as the source but the file im getting from the controller is Java file and the function to create byteString is of Scala file so had to use scala file in this func.
    Future.fromTry( Try{
      ByteString(file.toByteArray())
    }).flatMap { byteString =>
      Source.single(byteString).runWith(s3Sink) map { res =>
        AWSLocation(s"$bucket/$fileNameUUID", res.key)
      }
    }.recover {
      case ex: S3Exception =>
        logger.error("some message", ex)
        throw ex
      case ex: Throwable =>
        logger.error("some message", ex)
        throw ex
    }
  }
}

对齐文件类型的最佳方法是什么,以便我能够将字节字符串文件传递给我的源?

4

1 回答 1

2

看看FileIO.fromPath哪个会给你Source[ByteString, ...]java.nio.file.Path

于 2018-11-19T14:23:35.517 回答