How to post or upload a file to a url or servelet using java

It took me a while to find out how to do this. Things you need to do is not hard, but how to find out things you needed to do was hard. No where in the internet I could easily find a way to do this. Finally I came across a few examples where it uses java deprecated classes/methods to do it. With some more research I found a valid way to do it without using any deprecated classes/methods.

Here it is in the form of a function. I’ll just paste the function I created.

import java.io.File;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;

public static String uploadFile(File resourceUrl,String url) throws HttpException, IOException{
	File f = resourceUrl;
	PostMethod filePost = new PostMethod(url);
	Part[] parts = {new FilePart(f.getName(), f)};
	filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
	HttpClient client = new HttpClient();
	int status = client.executeMethod(filePost);
	String resultUUid=null;
	resultUUid = filePost.getResponseBodyAsString();
	filePost.releaseConnection();
	return resultUUid;
}

You will need either the

org.wso2.carbon.commons.httpclient-3.1.jar 
org.wso2.carbon.logging-1.0.jar
org.wso2.carbon.commons.codec-1.3.jar

or 

commons-httpclient-3.1.jar 
commons-logging-1.1.jar
commons-codec-1.3.jar

files as libraries to run this.

In the function

the “status” represents the status of the post call.If the call is successfull the value of this would be 200. If not it will contain the relevant error status value which you can look upon on the net as http status messages.

The “resultUUid” will contain the server response. In this case I’ve taken it as a string. You can get it as a stream also in case the respose is a very long one (like a file that needs to be downloaded)

Tags: , , , , , , , ,

7 Responses to “How to post or upload a file to a url or servelet using java”

  1. Coskan Says:

    Hi Saminda,
    I was looking for exactly the same thing. I managed to find org.wso2.carbon.commons.httpclient-3.1.jar and org.wso2.carbon.commons.codec-1.3.jar but not org.wso2.carbon.logging-1.0.jar. Could you e-mail this file to me.
    I want to send an .xml file from my local drive to my localhost.(I have Apache Tomcat 6.0 installed) I am new to this subject and don’t know how should I set my “String url” parameter for that.
    Thanks in advance.

  2. saikumar Says:

    Hi Guys,

    I done the same thing as you suggested it given me the status as “302”

    i send parameters to the method as
    File file12=new File(“c://new.txt”);
    uploadFile(file12,”http://localhost:8080/test”);

    pls suggest me whats the problem.

  3. samindaw Says:

    The status code 302 is related to url redirection being required. i.e. u might have to use the suggested url. This suggested url might be among the headers or also might be in the response body.
    If you have a web interface which did the uploading before try to see if the request is redirected from the browser to a different url. if you are using firefox, u can use the firebug to see the active connection the browser is making to the web server with different urls.

  4. Glenn N. Says:

    I set all three ‘commons’ JAR files on the classpath and compiled the program no problem, however when I try to run it I get the following error:

    C:\Users\67726e\Desktop>java test
    Exception in thread “main” java.lang.NoClassDefFoundError: test
    Caused by: java.lang.ClassNotFoundException: test
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    Could not find the main class: test. Program will exit.

    My code most certainly does have a main(String[] args) but for some reason it insists I do not. Do you have any idea why this is happening. Secondly, why do I actually need commons-logging and commons-codec?

  5. Vishal Kumar Aruru Says:

    I am getting 500 error when i am running the project in the unix environment, but in windows it is working fine in the eclipse IDE. Please suggest

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: