微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Akka-http中上传文件并获取Formfields

如何解决如何在Akka-http中上传文件并获取Formfields

我正在尝试通过akka-http上传文件,并使其可用于以下代码

def tempDestination(fileInfo: FileInfo): File =
  File.createTempFile(fileInfo.fileName,".tmp")

val route =
  storeUploadedFile("csv",tempDestination) {
    case (Metadata,file) =>      
      //Do my operation on the file.
      complete("File Uploaded. Status OK")
  }

但是我也想以发布的形式发送param1 / param2。

我尝试了以下操作,并且可以使用,但是我必须通过URL(http:// host:port / csv-upload?userid = arvind)发送参数

(post & path("csv-upload")) {
   storeUploadedFile("csv",tempDestination) {
     case (Metadata,file) =>
       parameters('userid) { userid =>
          //logic for processing the file
          complete(OK)
       }
   }
}
    

文件大小的限制约为200-300 MB。我在conf中添加了以下属性

 akka{
     http{
         parsing{
             max-content-length=200m
         }
     }
 }

有没有办法,我可以通过formFields指令获取参数?

我尝试了以下

fileUpload("csv") {
        case (Metadata,byteSource) =>
          formFields('userid) { userid =>
            onComplete(byteSource.runWith(FileIO.toPath(Paths.get(Metadata.fileName)))) {
              case Success(value) =>
                logger.info(s"${Metadata}")
complete(StatusCodes.OK)
              case Failure(exception) =>
                complete("failure")
                

但是,使用上面的代码,我遇到了以下异常

java.lang.IllegalStateException: Substream Source cannot be materialized more than once
    at akka.stream.impl.fusing.SubSource$$anon$13.setCB(StreamOfStreams.scala:792)
    at akka.stream.impl.fusing.SubSource$$anon$13.preStart(StreamOfStreams.scala:802)
    at akka.stream.impl.fusing.GraphInterpreter.init(GraphInterpreter.scala:306)
    at akka.stream.impl.fusing.GraphInterpreterShell.init(ActorgraphInterpreter.scala:593)

谢谢, Arvind

解决方法

我把它和某事一起工作:

  path("upload") {

    formFields(Symbol("payload")) { payload =>
      println(s"Server received request with additional payload: $payload")

      def tempDestination(fileInfo: FileInfo): File = File.createTempFile(fileInfo.fileName,".tmp.server")

      storeUploadedFile("binary",tempDestination) {
        case (metadataFromClient: FileInfo,uploadedFile: File) =>
          println(s"Server stored uploaded tmp file with name: ${uploadedFile.getName} (Metadata from client: $metadataFromClient)")
          complete(Future(FileHandle(uploadedFile.getName,uploadedFile.getAbsolutePath,uploadedFile.length())))
      }
    }
  }

完整示例: https://github.com/pbernet/akka_streams_tutorial/blob/master/src/main/scala/akkahttp/HttpFileEcho.scala

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。