Akka文件上传-在收到请求结束之前发送2xx“早期”响应

时间:2018-09-04 21:36:24

标签: scala file-upload akka-stream akka-http

我知道这里已经有人问过这个问题,但是我没有找到任何可行的解决方案。始终保持此警告状态:在收到请求结束之前发送2xx“早期”响应。

这是我的代码:

pathPrefix("upload") {
  (post & extractRequest) { _ => {
    extractRequestContext {
      requestCtx => {
        println(requestCtx.request.toString)
        implicit val materializer = requestCtx.materializer
        implicit val executionContext = requestCtx.executionContext
        fileUpload("file") {
          case (metadata, byteSource) => {

            val completesOnceUploadCompleted: Future[Done] =
              byteSource.runWith(FileIO.toPath(Paths.get(metadata.fileName))).map(
                iores => iores.status.get
              )

            val futureResponseBody = completesOnceUploadCompleted.map(res => res)
            complete(futureResponseBody)
          }
        }
      }
    }
  }

  }
}

请帮助我修复它。

1 个答案:

答案 0 :(得分:2)

我不确定潜在问题的原因。但是,一种“快速修复”方法是使用https://flutter.io/cookbook/navigation/passing-data/指令等待编写完成:

pathPrefix("upload") {
  post {    
    extractRequestContext { requestCtx => 
      println(requestCtx.request.toString)
      implicit val materializer = requestCtx.materializer
      implicit val executionContext = requestCtx.executionContext

      fileUpload("file") { (metadata, byteSource) =>

        val writeFileFut : Future[Try[Done]] = 
          byteSource.runWith(FileIO.toPath(Paths.get(metadata.fileName)))
                    .map(_.status)

        onComplete(writeFileFut) {
          case Success(statusTry) => statusTry match {
            case Success(done) => complete(StatusCodes.Ok)
            case Failure(ex) => complete(StatusCodes.InternalServerError -> ex.toString)
          }
          case Failure(ex) => complete(StatusCodes.InternalServerError -> ex.toString)
        }
      }
    }
  }
}