How to upload a file from Java to PHP over HTTP

Author: Veeresh Rudrappa. Date: Sep 14, 2012

Here is an easy way to upload any file from your Java application to a PHP site hosted somewhere. I had to do this for one my project in which I was required to upload a bunch of files based on a schedule of once in 24 hrs. I also had to implement a retry logic if the upload failed due to loss of network or some network congestion. I will blog on that logic some other time, but for now I'll show here how to upload a file from java and receive it in the PHP site.

Firstly, you would need to download a bunch of libraries. Download these jar files and add them to your java build path as external jars. Right Click on project --> properties --> Java Build path --> libraies --> add external jars.

Here is the Client side java code. Replace the URL with the correct server address where the PHP file is hosted. Also replace the source directory of the file you want to upload.

                                            import java.io.File;
                                            import org.apache.http.HttpEntity;
                                            import org.apache.http.HttpResponse;
                                            import org.apache.http.HttpVersion;
                                            import org.apache.http.client.HttpClient;
                                            import org.apache.http.client.methods.HttpPost;
                                            import org.apache.http.entity.mime.MultipartEntity;
                                            import org.apache.http.entity.mime.content.ContentBody;
                                            import org.apache.http.entity.mime.content.FileBody;
                                            import org.apache.http.impl.client.DefaultHttpClient;
                                            import org.apache.http.params.CoreProtocolPNames;
                                            import org.apache.http.util.EntityUtils;


                                            public class UploadFile {
                                              public static void upload() throws Exception {
    
		                                            String userHome=System.getProperty("user.home");
		                                            HttpClient httpclient = new DefaultHttpClient();
		                                            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		                                            HttpPost httppost = new HttpPost("http://www.xxx.xxxx.xxx/Projects/test/upload.php");
		                                            File file = new File(userHome+"/Hello.txt");
		                                            MultipartEntity mpEntity = new MultipartEntity();
		                                            ContentBody contentFile = new FileBody(file);
		                                            mpEntity.addPart("userfile", contentFile);
		                                            httppost.setEntity(mpEntity);
		                                            System.out.println("executing request " + httppost.getRequestLine());
		                                            HttpResponse response = httpclient.execute(httppost);
		                                            HttpEntity resEntity = response.getEntity(); 
		
		                                            if(!(response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
			                                            // Successfully Uploaded
		                                            }
		                                            else{
			                                            // Did not upload. Add your logic here. Maybe you want to retry.
		                                            }
		                                            System.out.println(response.getStatusLine());
		                                            if (resEntity != null) {
			                                            System.out.println(EntityUtils.toString(resEntity));
		                                            }
		                                            if (resEntity != null) {
			                                            resEntity.consumeContent();
		                                            }
		                                            httpclient.getConnectionManager().shutdown();
	                                            }
  
                                              public static void main(String[] args)
                                              {
	                                              try {
		                                            UploadFile.upload();
	                                            } catch (Exception e) {
	
		                                            e.printStackTrace();
	                                            }
                                              }
                                            }

                                    

Here is the PHP file to receive the uploaded file on the server side. Update the destination directory depending on where you want to store it.

                                            
                                    
Hope this helps :)
comments powered by Disqus