Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 228
Andrey Avatar asked Jan 04 '23 08:01

Andrey


1 Answers

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)
like image 54
Andrey Avatar answered Jan 06 '23 22:01

Andrey