0

I process a request which I then send to another endpoint. All work great except encoding for file name (it comes with corrupted characters if they are not typical).

I have figured out how to set UTF-8 for string items, however I do not know how to do that for FileBody class.

How can I set UTF-8 for file I send? Thanks!

I attached example of my Java code below

Map parameters = req.getParameterMap();

UploadedFile uploadedFile = (UploadedFile) parameters.get("file");

File serverFile = new File(uploadedFile.getServerFileName());
File clientFile = new File(serverFile.getParent() + java.io.File.separator + uploadedFile.getClientFileName());
serverFile.renameTo(clientFile);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", new FileBody(clientFile));
builder.addTextBody("field1", "Načrt", ContentType.create("text/plain", Charset.forName("UTF-8")));
Dmytro Pastovenskyi
  • 5,240
  • 5
  • 37
  • 56

2 Answers2

0

If nothing else works, you can change the entire encoding of all files handled by your program with this snippet of code at the start of your main:

System.setProperty("file.encoding", "UTF-8");
Field charset = Charset.class.getDeclaredField("defaultCharset");
charset.setAccessible(true);
charset.set(null, null);

I had to use this for an app that had to read/write files in both Linux and Windows, which used some shady libraries to interact with the files.

BlueMoon93
  • 2,910
  • 22
  • 39
0

Thanks to all.

I found a solution for me case. See it beow.

Map parameters = req.getParameterMap();

UploadedFile uploadedFile = (UploadedFile) parameters.get("file");

File serverFile = new File(uploadedFile.getServerFileName());
File clientFile = new File(serverFile.getParent() + java.io.File.separator + uploadedFile.getClientFileName());
serverFile.renameTo(clientFile);

MultipartEntityBuilder builder = MultipartEntityBuilder.create();

// fix <==========================
builder.setCharset(Charset.forName("UTF-8")).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

builder.addPart("file", new FileBody(clientFile));
builder.addTextBody("field1", "Načrt", ContentType.create("text/plain", Charset.forName("UTF-8")));
Dmytro Pastovenskyi
  • 5,240
  • 5
  • 37
  • 56