RESTeasy Fileupload vs Encoding

Encoding problems when implementing a RESTeasy file-upload are not uncommon. Why?
For text based content you usually pass the charset in the Content-Type Header of a HTTP message:

For a file-upload you usually use the Content-Type multipart/form-data. Multipart combines multiple parts and every part can have it’s own Content-Type:

If you add the correct Content-Type for every part it works out of the box. This can easily be tested with the RESTeasy Client:

It’s not so easy if you are using a client which can’t set the Content-Type for every part easily. One solution could be using a ContainerRequestFilter to overwrite the DefaultEncoding. In this example we’re checking for a custom header:

It’s getting really difficult if your client also cannot pass a custom header. This is unfortunately the case for the most common client: the HTML form. The w3c defines in a not that trivial algorithm how the client should determine the encoding. We can take advantage of the _charset_ field here. If there is following input field in a form the browser should populate the value with the currently used charset:

Once added to a form we can use it in our resource:

A full example can be found on Github. Originally published on teamwork.adorsys.de (german).