传递参数以及multipart / form-data上传表单(Java Http Post Upload) [英] Passing parameters along with a multipart/form-data upload form (Java Http Post Upload)
问题描述
我有一个代码库,目前使用Post上传文件,并且enctype为multipart / form-data。现在我需要包含一些表单项,即一些参数也将与文件上载一起传递。我创建了我的html表单,但我不能使用request.getParameter,因为它是一个多部分表单。有人可以建议我如何传递参数和我的上传文件。我提供以下代码。请建议我如何根据我的代码的兼容性来解决这个问题
I have a code base which currently uploads file using Post and has enctype as multipart/form-data. Now I need to include some form items i.e. 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. 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 );
}
}
推荐答案
如果 isFormField
on FileItemStream
返回true,则为正常字段。您可以使用 openStream
并将内容读入字符串。
If isFormField
on FileItemStream
returns true it's a normal field. You can use openStream
and read the contents into a String.
这样的事情:
FileItemStream item = iter.next();
if(item.isFormField()) {
// Normal field
String name = item.getFieldName();
String value = Streams.asString(item.openStream());
} else {
// File
}
Streams.asString
接受第二个参数,即要使用的charset编码,您可能需要指定一个适合您网站的参数。
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.
这篇关于传递参数以及multipart / form-data上传表单(Java Http Post Upload)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!