JSF 2.0: Mojarra and multipart/form-data (File Upload) [Glassfish]
Dennis GuseIt is a quite a mess that Mojarra doesn't support h:forms that use enctyp multipart/form-data, because you can't access possible available parts in the JSF Controllers.
The following wrapper extends a HttpServletRequest so that getParameter also uses available data in HttpServletRequest.getParts().
You can than access the HttpServletRequest via FacesContext.getCurrentInstance().getExternalContext() and use getParts own your own.
1import java.io.BufferedReader;
2import java.io.IOException;
3import java.io.InputStream;
4import java.io.InputStreamReader;
5import java.util.HashMap;
6import java.util.Map;
7import java.util.logging.Level;
8import java.util.logging.Logger;
9import javax.servlet.ServletException;
10import javax.servlet.http.HttpServletRequest;
11import javax.servlet.http.HttpServletRequestWrapper;
12import javax.servlet.http.Part;
13
14/**
15 * The mojarra implementation does not parse POST request that are multipart encoded,
16 * because the parameters are not accessable via <code>getParameter()</code>.
17 *
18 * This class extends the HttpServletRequest to provide access to the parameters
19 * which are encoded accessable via <code>getParts</code>.
20 *
21 * All parts are made visible that have <code>contentType == null && size < 300</code>.
22 *
23 * If the request is not multipart encoded, the wrapper doesn't modify the behavior of the original <code>HttpServletRequest</code>.
24 * @author dennis
25 */
26public class MultipartHTTPServletRequest extends HttpServletRequestWrapper {
27
28 protected Map<String, String> parameterParts = new HashMap<String, String>();
29
30 public MultipartHTTPServletRequest(HttpServletRequest request) {
31 super(request);
32
33 if (getContentType() == null) {
34 return;
35 }
36 if (!getContentType().toLowerCase().startsWith("multipart/")) {
37 return;
38 }
39 try {
40 for (Part i : getParts()) {
41 if (i.getContentType() == null && i.getSize() < 300) {
42 parameterParts.put(i.getName(), getData(i.getInputStream()));
43 }
44 }
45 } catch (IOException ex) {
46 Logger.getLogger(MultipartHTTPServletRequest.class.getName()).log(Level.SEVERE, null, ex);
47 } catch (ServletException ex) {
48 Logger.getLogger(MultipartHTTPServletRequest.class.getName()).log(Level.SEVERE, null, ex);
49 }
50 }
51
52 private static String getData(InputStream input) throws IOException {
53 String data = "";
54 String line = "";
55 BufferedReader reader = new BufferedReader(new InputStreamReader(input));
56 while ((line = reader.readLine()) != null) {
57 data += line;
58 }
59 return data;
60 }
61
62 @Override
63 public String getParameter(String name) {
64 String result = super.getParameter(name);
65 if (result == null) {
66 return parameterParts.get(name);
67 }
68 return result;
69 }
70}