Encoding issues while uploading files with Primefaces

Goal

Fix encoding issues with uploaded files that contain special characters such as ‘ç’ or ‘ã’, when using Primefaces fileupload component

Description

The situation may be summarized as follows:

  • We have a Primefaces fileUpload component in a page
  • After uploading a file whose name is something like ‘Declaração.pdf’, we end up with a strange name where the “special characters” ‘ç’ and ‘ã’ are not properly converted

How to

If you have this kind of situation in your project, you need to specify the encoding/charset for your HTTP request.

The option I prefer, is the creation of a filter such as the one below that will force all HTTP requests to be encoded in UTF-8

@WebFilter(filterName = "CharacterEncodingFilter", urlPatterns = "*.xhtml")
public class CharacterEncodingFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    request.setCharacterEncoding("UTF-8");
    chain.doFilter(request, response);
  }

  @Override
  public void destroy() {
  }
}

Explanations

If we use the previously shown filter, all HTTP requests for our pages (notice that I’m using the mapping .xhtml for the Faces servlet) will be encoded in UTF-8. Therefore, any special characters such as the ones in the filename discussed in this recipe will be properly handled.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s