试图将java文件转换为字节串以在流中使用

时间:2018-11-19 13:48:05

标签: java scala akka akka-stream alpakka

我正在创建一个向我发送文件的api,然后将它们上传到S3,然后使用akka-stream-alpakka-s3库通过流使用im来实现。

我的问题是我可以在控制器中将文件转换为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服务func中,我只使用scala文件,因为它具有“ toByteArray” func,我需要它作为源代码,它看起来像这样:

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

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

1 个答案:

答案 0 :(得分:2)

看看FileIO.fromPath,它将为您提供Source[ByteString, ...]中的java.nio.file.Path