Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encode filename in MultipartEntityBuilder

I am trying a file upload API using HttpPost and MultipartEntityBuilder. Following is the code I have used.

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);
builder.addBinaryBody(<fileFieldName>, <byteArray>, ContentType.TEXT_PLAIN, <fileName>);

File gets uploaded correctly. But when file name contains non-ASCII characters, it gets uploaded with name "????.jpg". Tried the solution given here https://stackoverflow.com/a/25870301/3271472. But it didn't solve my problem. Please assist.

like image 471
Sabitha Avatar asked Oct 14 '25 13:10

Sabitha


2 Answers

This worked for me:

MultipartEntityBuilder b = MultipartEntityBuilder.create();
b.addPart("file", new FileBody(<FILE>, <CONTENTTYPE>, <FILENAME>)).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
b.setCharset(StandardCharsets.UTF_8);

Just replace <> values with yours...

like image 175
riva Avatar answered Oct 17 '25 02:10

riva


builder.setMode(HttpMultipartMode.RFC6532); did the magic in my case. Also check if your server accepts UTF-8 encoded filename. In my case it was Apache Sling Post Servlet and I had to update default server encoding.

    FileBody fileBody = new FileBody(file, ContentType.create("application/pdf"), "Příliš sprostý vtip.pdf");

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.RFC6532);
    builder.addPart("Příliš sprostý vtip.pdf", fileBody);
    builder.addPart("žabička2", new StringBody("žabička", ContentType.MULTIPART_FORM_DATA.withCharset("UTF-8")));

    HttpEntity entity = builder.build();        
    post.setEntity(entity);
    CloseableHttpClient client = HttpClients.createDefault();
    HttpResponse response = client.execute(post);
like image 40
Jarda Pavlíček Avatar answered Oct 17 '25 03:10

Jarda Pavlíček



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!