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

trying to convert java file to bytestring for using in stream

我正在创建一个 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
    }
  }
}

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

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