Search code examples
javafile-uploadapache-commons

Get post parameter before upload


When I use Commons FileUpload the method parseRequest(request) uploads files and also reads additional post parameters. So I can get parameter values only after uploading the files. The problem is that I need those parameter values before uploading the files (one of the parameters is upload_path).

Is there any way to get post parameters first from multipart content and then start uploading to the correct folder?

(request.getParameter(name) will return null for multipart content).

Thanks in advance!


Solution

  • This works for me, in first pass I check all parameters, after that I take the non form fields for download.

    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator( request );
    
    while ( iter.hasNext() ) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        InputStream stream = item.openStream();
    
        if ( item.isFormField() ) {
            byte[] buffer = new byte[ 128 ];
            int len = stream.read( buffer );
            String value = new String( buffer, 0,len );
            if ( name.equals( "name" ) ) {
                filename  = value;
            }
            System.err.println( "Form field " + name + " with value " + value + " detected." );
            stream.close();
        }
    }