java 如何使用 Apache Commons 以多部分形式读取其他参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/350794/
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
How can I read other parameters in a multipart form with Apache Commons
提问by pkaeding
I have a file upload form that is being posted back to a servlet (using multipart/form-data encoding). In the servlet, I am trying to use Apache Commons to handle the upload. However, I also have some other fields in the form that are just plain fields. How can I read those parameters from the request?
我有一个文件上传表单,它被回发到一个 servlet(使用 multipart/form-data 编码)。在 servlet 中,我尝试使用 Apache Commons 来处理上传。但是,我在表单中还有一些其他字段,它们只是普通字段。如何从请求中读取这些参数?
For example, in my servlet, I have code like this to read in the uplaoded file:
例如,在我的 servlet 中,我有这样的代码要在上传的文件中读取:
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
Iterator /* FileItem */ items = upload.parseRequest(request).iterator();
while (items.hasNext()) {
FileItem thisItem = (FileItem) items.next();
... do stuff ...
}
回答by stian
You could try something like this:
你可以尝试这样的事情:
while (items.hasNext()) {
FileItem thisItem = (FileItem) items.next();
if (thisItem.isFormField()) {
if (thisItem.getFieldName().equals("somefieldname") {
String value = thisItem.getString();
// Do something with the value
}
}
}
回答by Edward Verenich
Took me a few days of figuring this out but here it is and it works, you can read multi-part data, files and params, here is the code:
我花了几天的时间才弄明白这个问题,但在这里它确实有效,您可以读取多部分数据、文件和参数,这是代码:
try {
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iterator = upload.getItemIterator(req);
while(iterator.hasNext()){
FileItemStream item = iterator.next();
InputStream stream = item.openStream();
if(item.isFormField()){
if(item.getFieldName().equals("vFormName")){
byte[] str = new byte[stream.available()];
stream.read(str);
full = new String(str,"UTF8");
}
}else{
byte[] data = new byte[stream.available()];
stream.read(data);
base64 = Base64Utils.toBase64(data);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
回答by Edward Verenich
Did you try request.getParam() yet?
你试过 request.getParam() 了吗?

