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