Java 我的 Servlet 如何从 multipart/form-data 表单接收参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9667169/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:52:38  来源:igfitidea点击:

How can my Servlet receive parameters from a multipart/form-data form?

javaservletsparametersmultipartform-data

提问by Bolaum

I have a page that has this piece of code:

我有一个包含这段代码的页面:

<form action="Servlet" enctype="multipart/form-data">
<input type="file" name="file">
<input type="text" name="text1">
<input type="text" name="text2">
</form>

When I use request.getParameter("text1");in my Servlet it shows null. How can I make my Servlet receive the parameters?

当我request.getParameter("text1");在我的 Servlet 中使用时,它显示为空。如何让我的 Servlet 接收参数?

回答by Francisco Paulo

回答by gorjusborg

All the request parameters are embedded into the multipart data. You'll have to extract them using something like Commons File Upload: http://commons.apache.org/fileupload/

所有请求参数都嵌入到多部分数据中。您必须使用类似 Commons File Upload 的方法提取它们:http: //commons.apache.org/fileupload/

回答by qiangbro

Pleepleus is right, commons-fileupload is a good choice.
If you are working in servlet 3.0+ environment, you can also use its multipart support to easily finish the multipart-data parsing job. Simply add an @MultipartConfigon the servlet class, then you can receive the text data by calling request.getParameter(), very easy.

Pleepleus 是对的,commons-fileupload 是一个不错的选择。
如果您在 中工作servlet 3.0+ environment,您还可以使用其多部分支持轻松完成多部分数据解析工作。只需@MultipartConfig在 servlet 类上添加一个,就可以通过调用 request 来接收文本数据。getParameter(), 好简单。

Tutorial - Uploading Files with Java Servlet Technology

教程 - 使用 Java Servlet 技术上传文件

回答by DejanR

You need to send the parameter like this:

您需要像这样发送参数:

writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"" + urlParameterName + "\"" )
                .append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF);
writer.append(urlParameterValue).append(CRLF);
writer.flush();

And on servlet side, process the Form elements:

在 servlet 端,处理 Form 元素:

items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
       item = (FileItem) iter.next();
       if (item.isFormField()) {
          name = item.getFieldName(); 
          value = item.getString();

   }}