Xinlong
Xinlong

Reputation: 23

Akka HTTP server receives file with other fields

I have created a small Akka HTTP server to receive an uploaded file.

path("upload"){
    uploadedFile("csv"){
        case (metadata, file) =>{
            println("file received " + file.length() );
            complete("hahahah")
        }
    }
}

I can receive the file successfully but I cannot access other fields in this POST request. The field "csv" contains the file to be uploaded, while another field, "name", contains the user-defined name. I cannot access the data in "name". Can anybody give me some clues about how to get it?

Upvotes: 2

Views: 1495

Answers (1)

Leonard
Leonard

Reputation: 561

You can use fromFields('user) to get user name. But unfortunately you will get this exception: java.lang.IllegalStateException: Substream Source cannot be materialized more than once It's known issue: https://github.com/akka/akka-http/issues/90

As workaround, you can use toStrictEntity directive:

 toStrictEntity(3.seconds) {
   formFields('user) { (user) =>
     uploadedFile("csv") {
       case (metadata, file) => {
         println(s"file received by $user" + file.length())
           complete("hahahah")
         }
       }
     }
   }
 }

I don't think it's a good idea because you will read the entire request entity into memory and it works if you have the small entity.

As a better solution, you can implement your own uploadedFile directive that will extract needed parts and fields from your multipart form data, see uploadedFile source code as example: https://github.com/akka/akka-http/blob/v10.0.10/akka-http/src/main/scala/akka/http/scaladsl/server/directives/FileUploadDirectives.scala

Upvotes: 2

Related Questions