javautf-8multipartentity

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.


Solution

  • 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...