Java 在 Servlet 中解析传入的 multipart/form-data 参数的便捷方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3337056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convenient way to parse incoming multipart/form-data parameters in a Servlet
提问by atuser
Is there any convenient way to read and parse data from incoming request.
有什么方便的方法可以从传入的请求中读取和解析数据。
E.g client initiate post request
例如客户端发起发布请求
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
PrintWriter writer = null;
try {
OutputStream output = connection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!
// Send normal param.
writer.println("--" + boundary);
writer.println("Content-Disposition: form-data; name=\"param\"");
writer.println("Content-Type: text/plain; charset=" + charset);
writer.println();
writer.println(param);
I'm not able to get param using request.getParameter("paramName")
. The following code
我无法使用request.getParameter("paramName")
. 以下代码
BufferedReader reader = new BufferedReader(new InputStreamReader(
request.getInputStream()));
StringBuilder sb = new StringBuilder();
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
}
however displays the content for me
但是为我显示内容
-----------------------------29772313742745
Content-Disposition: form-data; name="name"
J.Doe
-----------------------------29772313742745
Content-Disposition: form-data; name="email"
[email protected]
-----------------------------29772313742745
What is the best way to parse incoming request? I don't want to write my own parser, probably there is a ready solution.
解析传入请求的最佳方法是什么?我不想编写自己的解析器,可能有现成的解决方案。
采纳答案by BalusC
multipart/form-data
encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded
encoding. When using a different encoding, the request.getParameter()
calls will all return null
. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts()
instead. Also see this blogfor extended examples.
multipart/form-data
3.0 之前的 Servlet API 默认不支持编码请求。Servlet API 默认使用application/x-www-form-urlencoded
编码解析参数。当使用不同的编码时,request.getParameter()
调用都会返回null
. 如果您已经使用 Servlet 3.0(Glassfish 3、Tomcat 7等),则可以HttpServletRequest#getParts()
改用。另请参阅此博客以获取扩展示例。
Prior to Servlet 3.0, a de factostandard to parse multipart/form-data
requests would be using Apache Commons FileUpload. Just carefully read its User Guideand Frequently Asked Questionssections to learn how to use it. I've posted an answer with a code example before here(it also contains an example targeting Servlet 3.0).
在 Servlet 3.0 之前,解析请求的事实上的标准multipart/form-data
是使用Apache Commons FileUpload。只需仔细阅读其用户指南和常见问题部分,即可了解如何使用它。我之前在这里发布了一个带有代码示例的答案(它还包含一个针对 Servlet 3.0 的示例)。
回答by renura
Solutions:
解决方案:
Solution A:
解决方案一:
- Download http://www.servlets.com/cos/index.html
- Invoke getParameters() on
com.oreilly.servlet.MultipartRequest
- 下载http://www.servlets.com/cos/index.html
- 调用 getParameters()
com.oreilly.servlet.MultipartRequest
Solution B:
解决方案B:
- Download http://jakarta.Apache.org/commons/fileupload/
- Invoke readHeaders() in
org.apache.commons.fileupload.MultipartStream
- 下载http://jakarta.Apache.org/commons/fileupload/
- 在中调用 readHeaders()
org.apache.commons.fileupload.MultipartStream
Solution C:
解决方案 C:
- Download http://users.boone.net/wbrameld/multipartformdata/
- Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData
- 下载http://users.boone.net/wbrameld/multipartformdata/
- 在 com.bigfoot.bugar.servlet.http.MultipartFormData 上调用 getParameter
Solution D:
解决方案 D:
Use Struts. Struts 1.1 handles this automatically.
使用支柱。Struts 1.1 会自动处理这个问题。
Reference: http://www.jguru.com/faq/view.jsp?EID=1045507
参考:http: //www.jguru.com/faq/view.jsp?EID= 1045507
回答by Luca Rasconi
Not always there's a servlet before of an upload (I could use a filter for example). Or could be that the same controller ( again a filter or also a servelt ) can serve many actions, so I think that rely on that servlet configuration to use the getPart method (only for Servlet API >= 3.0), I don't know, I don't like.
在上传之前并不总是有一个 servlet(例如,我可以使用过滤器)。或者可能是同一个控制器(又是一个过滤器或一个 servelt )可以提供许多操作,所以我认为依靠那个 servlet 配置来使用 getPart 方法(仅适用于 Servlet API >= 3.0),我不知道,不喜欢。
In general, I prefer independent solutions, able to live alone, and in this case http://commons.apache.org/proper/commons-fileupload/is one of that.
一般来说,我更喜欢独立的解决方案,能够独自生活,在这种情况下 http://commons.apache.org/proper/commons-fileupload/就是其中之一。
List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multiparts) {
if (!item.isFormField()) {
//your operations on file
} else {
String name = item.getFieldName();
String value = item.getString();
//you operations on paramters
}
}