Andrey
Andrey

Reputation: 341

Upload file with multipart POST request using Apache Http Async Client

I am trying to upload a 260k image file as part of multipart form using Apache HttpAsyncClient library.

I create my form this way:

val multipartEntityBuilder = new MultipartEntityBuilder
multipartEntityBuilder.addBinaryBody("file", file)
val multipartEntity = multipartEntityBuilder.build()

And then I receive a ContentTooLongException when performing request basically because of this line in the library's source code: https://github.com/apache/httpclient/blob/4.5.3/httpmime/src/main/java/org/apache/http/entity/mime/MultipartFormEntity.java#L102

I searched a lot, but didn't find any explanation why this limitation for contentLength is present in code. Maybe someone could explain it? And my second question: what is the proper way to make an upload request for a file larger than 25 kb?

Thanks!

Upvotes: 6

Views: 2141

Answers (1)

Andrey
Andrey

Reputation: 341

Found the solution: create inputStream over file and wrap the multipart entity with BufferedHttpEntity and then pass this buffered entity to request:

val multipartEntityBuilder = MultipartEntityBuilder.create()
multipartEntityBuilder.addBinaryBody("file", new FileInputStream(file), ContentType.DEFAULT_BINARY, name)
val multipartEntity = multipartEntityBuilder.build()
val entity = new BufferedHttpEntity(multipartEntity)

Upvotes: 10

Related Questions