简体   繁体   中英

Akka file upload - Sending an 2xx 'early' response before end of request was received

I know this question has been asked here already, but I haven't found any working solution to the problem. Keep getting this WARNING all the time: Sending an 2xx 'early' response before end of request was received.

Here is my code:

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

  }
}

Please help me fixing it.

I am not sure of the cause of the underlying problem. However, one "quick fix" would be to use the onComplete directive to wait for the writing to complete:

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

I had the same issue and simply adding implicit request: Request[AnyContent] => (which I had by mistake removed) solved it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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