繁体   English   中英

如何在akka-http中上传文件和获取表单域

[英]How to upload files and get formfields in akka-http

我正在尝试通过 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)

谢谢, 阿文德

我得到了这样的工作:

  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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM