How can I read other parameters in a multipart form with Apache Commons

我的未来我决定 提交于 2019-12-10 18:16:43

问题


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?

For example, in my servlet, I have code like this to read in the uplaoded file:

    // 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 ...
    }

回答1:


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
            }
        }

    }



回答2:


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();
    }



回答3:


Did you try request.getParam() yet?



来源:https://stackoverflow.com/questions/350794/how-can-i-read-other-parameters-in-a-multipart-form-with-apache-commons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!