Category : Android | Author : Chtiwi Malek | First posted : 5/30/2012 | Updated : 12/6/2012
Tags : android, upload, file, http, post, data, server, php, .net, aspx, c#, phone, device
Upload Files from Android to a Website/Http Server using Post

Upload Files from Android to a Website/Http Server using Post

In this tutorial I will write an Android class that can be used to upload a File (image, mp3, mp4, text file...) from an android device to a Http web server along with a title and a description using the POST method, I will also write the server side code to read the data sent by our android class.

First we need to have the permission to access internet, so we have to add this line to the AndroidManifest.xml (just after the application section)

<uses-permission android:name="android.permission.INTERNET" />

I will call our class (HttpFileUpload), so just create the file HttpFileUpload.java and copy the code below and set your package name (the 1st line):
package my.package.name;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.util.Log;
	
public class HttpFileUpload implements Runnable{
        URL connectURL;
        String responseString;
        String Title;
        String Description;
        byte[ ] dataToServer;
        FileInputStream fileInputStream = null;

        HttpFileUpload(String urlString, String vTitle, String vDesc){
                try{
                        connectURL = new URL(urlString);
                        Title= vTitle;
                        Description = vDesc;
                }catch(Exception ex){
                    Log.i("HttpFileUpload","URL Malformatted");
                }
        }
	
        void Send_Now(FileInputStream fStream){
                fileInputStream = fStream;
                Sending();
        }
	
        void Sending(){
                String iFileName = "ovicam_temp_vid.mp4";
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                String Tag="fSnd";
                try
                {
                        Log.e(Tag,"Starting Http File Sending to URL");
	
                        // Open a HTTP connection to the URL
                        HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
	
                        // Allow Inputs
                        conn.setDoInput(true);
	
                        // Allow Outputs
                        conn.setDoOutput(true);
	
                        // Don't use a cached copy.
                        conn.setUseCaches(false);
	
                        // Use a post method.
                        conn.setRequestMethod("POST");
	
                        conn.setRequestProperty("Connection", "Keep-Alive");
	
                        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
	
                        DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
	
                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(Title);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + lineEnd);
	                        
                        dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(Description);
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + lineEnd);
	                        
                        dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
                        dos.writeBytes(lineEnd);
	
                        Log.e(Tag,"Headers are written");
	
                        // create a buffer of maximum size
                        int bytesAvailable = fileInputStream.available();
	                        
                        int maxBufferSize = 1024;
                        int bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        byte[ ] buffer = new byte[bufferSize];
	
                        // read file and write it into form...
                        int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
	
                        while (bytesRead > 0)
                        {
                                dos.write(buffer, 0, bufferSize);
                                bytesAvailable = fileInputStream.available();
                                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                                bytesRead = fileInputStream.read(buffer, 0,bufferSize);
                        }
                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
	
                        // close streams
                        fileInputStream.close();
	                        
                        dos.flush();
	                        
                        Log.e(Tag,"File Sent, Response: "+String.valueOf(conn.getResponseCode()));
	                         
                        InputStream is = conn.getInputStream();
	                        
                        // retrieve the response from server
                        int ch;
	
                        StringBuffer b =new StringBuffer();
                        while( ( ch = is.read() ) != -1 ){ b.append( (char)ch ); }
                        String s=b.toString();
                        Log.i("Response",s);
                        dos.close();
                }
                catch (MalformedURLException ex)
                {
                        Log.e(Tag, "URL error: " + ex.getMessage(), ex);
                }
	
                catch (IOException ioe)
                {
                        Log.e(Tag, "IO error: " + ioe.getMessage(), ioe);
                }
        }
	
        @Override
        public void run() {
                // TODO Auto-generated method stub
        }
}
Here’s the function to call the HttpFileUpload and Start sending the file and the data :
public void UploadFile(){
try {
    // Set your file path here
    FileInputStream fstrm = new FileInputStream(Environment.getExternalStorageDirectory().toString()+"/DCIM/file.mp4");

    // Set your server page url (and the file title/description)
    HttpFileUpload hfu = new HttpFileUpload("http://www.myurl.com/fileup.aspx", "my file title","my file description");

    hfu.Send_Now(fstrm);

  } catch (FileNotFoundException e) {
    // Error: File not found
  }
}
 And here’s the server side code to read the File and the data (title and description). In this example the language used is c# .net, but the web server can be any language: php, asp, vb aspx, java…
protected void Page_Init(object sender, EventArgs e)
{
  string vTitle = "";
  string vDesc = "";
  string FilePath = Server.MapPath("/files/cur_file.mp4");        

  if (!string.IsNullOrEmpty(Request.Form["title"]))
  {
    vTitle = Request.Form["title"];
  }
  if (!string.IsNullOrEmpty(Request.Form["description"]))
  {
    vDesc = Request.Form["description"];
  }
	
  HttpFileCollection MyFileCollection = Request.Files;
  if (MyFileCollection.Count > 0)
  {
    // Save the File
    MyFileCollection[0].SaveAs(FilePath);
  }
}
Have fun and don't hesitate to ask me any questions or send me your thoughts.
About the author :
Malek Chtiwi is the man behind Codicode.com
34 years old full stack developer.
Loves technology; but also likes design, photography and composing music.
Comments & Opinions :
the code of server side
Hi Chtiwi Malek

Thanks for your article
Could you suggest me how to write the server side code by jsp ?
- by Jordanhsu on 6/28/2012
error
hi,
help me pls i have server on iis 6
and have this error
"method does not support a request body: POST" in
this part DataOutputStream dos = new DataOutputStream(conn.getOutputStream());


can you help me ?
- by Reynor 77 on 9/9/2012
Thank You
You help me, Thank
- by Bhumi Ph on 12/25/2012
Thanks a lot!
About two days i'am trying to upload image to server (vkontakte), but all attemps was failed.
After using your code all is ok.
I do not know what the difference and where my mistake (but i'll find it).
anyway - thanks again.
- by Eugene on 1/17/2013
Hi Eugene! I also killed 2 days to post image on vkontakte wall, but still not succeeded. I always get {"server":323527,"photo":"[]","hash":"ece54ef43d9b5928c8ff9ad9ab56ef0c"} as a result of POST http request. This code did'nt help either. Could you please share you piece of code that makes posting. Thanks!
- by Nik on 5/30/2013
great stuff, but there must be an easier way these days....
there must be a simpler method these days.

in html5 it looks a lot easier, as you can use the FormData object
(example from: https://hacks.mozilla.org/2010/05/formdata-interface-coming-to-firefox/ )
// aFile could be from an input type="file" or from a Dragged'n Dropped file
var formdata = new FormData();
formdata.append("nickname", "Foooobar"); 
formdata.append("website", "http://hacks.mozilla.org");
formdata.append("media", aFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://foo.bar/upload.php");  
xhr.send(formdata);

but how would you do this in Android? perhaps using a combination of a webview (html + javascript) and android javacode for selecting the image, or receiving the image from a send image (share image) intent.
- by holo deck supervisor on 2/16/2013
Out of memory on a xxxxxx (bytes) allocation
I used your posted code. When i upload file (20MB), it throws exception. Please help me! thanks in advance.
- by duong on 2/20/2013
Networkstrictmode
Hi,
I get "02-20 16:25:52.338: E/AndroidRuntime(24527): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dowrgv.picturesapp/com.dowrgv.picturesapp.GalleryActivity}: android.os.NetworkOnMainThreadException " with approximately no modified code except using a separate class...

- by rgvneil on 2/20/2013
do not know some details...
Hi,

1."the function to call the HttpFileUpload and Start sending the file and the data" called public void UploadFile() should put where in android to call,
2."my file title" means file name ?,
3. "my file description" is what?
4. in HttpFileUpload class whose "green charactors" i need to change for my case , like my file name etc.
	
conn.setRequestProperty("Connection", "Keep-Alive");

conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"title\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Title);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"description\""+ lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(Description);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + iFileName +"\"" + lineEnd);
i know ask too many questions to be rude,but i really need ur help
- by Aqua on 5/23/2013
Php implimentation
The code works great. Maybe you need to check the permissions of the temp, and uploads directories on your server. However, if using php as the server side language, the following is the code responsible for transfering your file to the uploads directory. You must have either the 'temp' or 'tmp' folder on your server and they should be publicly accessible. that's how i made mine work

<?php
//takes care of remote file uploads

//start upload
$file_path = "uploads/";
     
    $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
    if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
        echo "success";
    } else{
        echo "fail";
    }

?>
- by larrytech on 10/13/2014
can you send the source code of all this work plz....... at omaimatauqeer@gmail.com
- by omaima on 4/27/2016
Add parameters
Sir how to add parameters along with the image in above code.
- by Amir on 10/27/2014
Special characters
Hi,
Several parts in your post make me very confused, I don't understand the meaning of:
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
and also the way you have used them.
Please explain to me in details.
Thanks !
- by DucIT on 6/18/2015
Request.form is empty after posting file
Hello hopfuly you can help me
Actually I found for now only your example with ASPX
My problem is that Im posting from android APP file directly to the web site - no error everything seems to be normal
But 
Request.Form 
is empty
When I use imput tag with runat server then I see the file.
Im using simple APP from APP inventor2 with WEB component
I successfully posted file but my web site didnt see it. Do you have idea why?
I would be grateful for any help you can provide I realy dont understand why on PHP platfom its working and on the ASPX not.
I have also prepared the application in the C# but I fased the same problem
ASPX scrip didnt see the POSTED file.
- by Radek Prachfeld on 11/12/2015
Getting error 200
Hello,
Thanks very much for the code.
I am trying to send a file/picture that is within a particular folder within my phone, to a server.
On the server side I have written some PHP and I know that the directory where I want the picture to be copied to has the correct permissions. I am able to send a picture from an iOS device.

I get a server code of 200 using your code, and the tells me the picture did not save...
Would you know why this is? 
Thanks very much
- by Ana on 12/11/2015
How to upload word,pdf files to server from andoid
sir,
I am trying whole day to upload text file such as pdf,word files to my local host.But i could not do it.If you have any code which perform same peration please send it to me.
Thank you
- by shyam on 2/14/2016
NEED PHP CODE INSTEAD OF C# !!!!
can u give the php code instead of the c# code...pleeeassee
- by tuhin on 3/10/2016
Can it work with Wordpress?
Is it available as a WordPress plugin? I am looking for something similar but couldn't find a good Wordpress plugin for my site https://www.startupguys.net
- by Sophia Martin on 9/14/2017
How can i get the response of sended request?
I want to read the response of sended request. How can i take it?
- by Balavandi on 8/27/2019
How to Receive file using WCF webMethod
Dear, Please give me the code to Receiving file using WCF webMethod. 
- by R SUtharshan on 12/17/2019
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :