11.9. Uploading Files with a Multipart POST

Problem

You need to upload a file or a set of files with an HTTP multipart POST.

Solution

Create a MultipartPostMethod and add File objects as parameters using addParameter( ) and addPart( ). The MultipartPostMethod creates a request with a Content-Type header of multipart/form-data, and each part is separated by a boundary. The following example sends two files in an HTTP multipart POST:

               import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;

HttpClient client = new HttpClient( );
        
// Create POST method
String weblintURL = "http://ats.nist.gov/cgi-bin/cgi.tcl/echo.cgi";
MultipartPostMethod method = 
    new MultipartPostMethod( weblintURL );

File file = new File( "data", "test.txt" );
               File file2 = new File( "data", "sample.txt" );
               method.addParameter("test.txt", file );
               method.addPart( new FilePart( "sample.txt", file2, "text/plain", "ISO-8859-1" ) ); 

// Execute and print response
client.executeMethod( method );
String response = method.getResponseBodyAsString( );
System.out.println( response );

method.releaseConnection( );

Two File objects are added to the MultipartPostMethod using two different methods. The first method, addParameter( ), adds a File object and sets the file name to test.txt. The second method, addPart(), adds a FilePart object to the MultipartPostMethod ...

Get Jakarta Commons Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.