[英]Passing parameters along with a multipart/form-data upload form (Java Http Post Upload)
I have a code base which currently uploads file using Post and has enctype as multipart/form-data.我有一个代码库,目前使用 Post 上传文件,并且 enctype 为 multipart/form-data。 Now I need to include some form items ie some parameters will also be passed along with the file upload.
现在我需要包含一些表单项,即一些参数也将与文件上传一起传递。 I have my html form created out but I cannot use request.getParameter because it is a multipart form.
我创建了我的 html 表单,但我不能使用 request.getParameter 因为它是一个多部分表单。 Could anyone suggest me how do I pass parameters along with my upload file.
谁能建议我如何将参数与上传文件一起传递。 I am providing the codes below.
我提供下面的代码。 Please suggest me how to get around based on compatibility of my codes
请根据我的代码的兼容性建议我如何解决
if (!ServletFileUpload.isMultipartContent(request)) {
throw new CustomUploadException("Not a file upload request");
}
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext())
{
FileItemStream item = iter.next();
if (item.isFormField() == false &&
item.getFieldName().equalsIgnoreCase("xmlfile"))
{
String fileName = item.getName();
myBean.setFileName(fileName );
}
}
If isFormField
on FileItemStream
returns true it's a normal field.如果
FileItemStream
上的isFormField
返回 true,则它是一个普通字段。 You can use openStream
and read the contents into a String.您可以使用
openStream
并将内容读入字符串。
Something like this:像这样的东西:
FileItemStream item = iter.next();
if(item.isFormField()) {
// Normal field
String name = item.getFieldName();
String value = Streams.asString(item.openStream());
} else {
// File
}
Streams.asString
takes a second parameter which is the charset encoding to use, you might need to specify one that is suitable for your site. Streams.asString
采用第二个参数,它是要使用的字符集编码,您可能需要指定一个适合您的站点的参数。
To send a parameter with a FileUpload it just needs to be added in the URL within the setAction method As follows:要使用 FileUpload 发送参数,只需将其添加到setAction方法中的URL中,如下所示:
formPanel.setAction("< ProjectURL >/< YourServletName >?< YourParameterName > ="+parameter); formPanel.setAction("< ProjectURL >/< YourServletName >?< YourParameterName > ="+parameter);
And in your servlet simply get the parameter as follows:在您的 servlet 中,只需按如下方式获取参数:
req.getParameter("< YourParameterName > "); req.getParameter("< YourParameterName > ");
Hope it helps;-)希望能帮助到你;-)
Similar solutions:类似的解决方案:
FileItemStream item = iter.next();
if(item.isFormField()) {
String value = item.getString();
}
or或者
FileItemStream item = iter.next();
if(item.isFormField()) {
InputStream name = item.getInputStream();
String value = Streams.asString(name);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.