Friday, January 25, 2008

Yesterday, the whole day i was trying to post a file to a php server. The whole day and evening i tried and failed. I googled, searched in forum and did a lot of other stuffs. I couldn't succed, at last when i was frustrated on me, then i found another tutorial in a forum, this time it worked. mu ha ha :) (Copy paste rulllzz, so i should never try myself anything :(). The code simulates file posting to a php server. So it will work with servers where file upload from a server is supported. Here goes the code

The php code used in server

< ?php

$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";

? >

The android code goes here


import org.apache.commons.codec.binary.Base64;
import org.apache.http.util.ByteArrayBuffer;

import android.util.Log;

public class HttpFileUploader implements Runnable{

URL connectURL;
String params;
String responseString;
InterfaceHttpUtil ifPostBack;
String fileName;
byte[] dataToServer;

HttpFileUploader(String urlString, String params, String fileName ){
connectURL = new URL(urlString);
}catch(Exception ex){
this.params = params+"=";
this.fileName = fileName;


void doStart(FileInputStream stream){
fileInputStream = stream;

FileInputStream fileInputStream = null;
void thirdTry(){
String exsistingFileName = "asdf.png";

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String Tag="3rd";
//------------------ CLIENT REQUEST

Log.e(Tag,"Starting to bad things");
// Open a HTTP connection to the URL

HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();

// Allow Inputs

// Allow Outputs

// Don't use a cached copy.

// Use a post method.

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=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + 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 =, 0, bufferSize);

while (bytesRead > 0)
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead =, 0, bufferSize);

// send multipart form data necesssary after file data...

dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// close streams
Log.e(Tag,"File is written");

InputStream is = conn.getInputStream();
// retrieve the response from server
int ch;

StringBuffer b =new StringBuffer();
while( ( ch = ) != -1 ){
b.append( (char)ch );
String s=b.toString();

catch (MalformedURLException ex)
Log.e(Tag, "error: " + ex.getMessage(), ex);

catch (IOException ioe)
Log.e(Tag, "error: " + ioe.getMessage(), ioe);


Many of the headers included in the above file is not required, i was trying and failing :).

Now to upload file here is the java code from my activity class

public void uploadFile(){

try {
FileInputStream fis =this.openFileInput(NAME_OF_FILE);
HttpFileUploader htfu = new HttpFileUploader("","noparamshere", NAME_OF_FILE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block

The main advantage is that the way it posts data to the server is similar to a Html Form posting data to a php server. Hope it might be useful for me in future, so i blogged it, if others are helped then that would be great.You can visit for more and more tutorials. Thanks for reading my bad post :)


  1. Anonymous said...
    Good explanation! Exactly what I am looking for, Thanks
    Anonymous said...
    could you explain in brief bcz i am very new to java. but i want this program in my flex project
    Shimul said...
    i dont know how flex works so i think i cannot help u much
    dhileep said...
    no need of flex knowledge required.
    i call applet function from flex.

    you have upload my 'C' drive .doc file to my server in that function

    my mail id is
    dhileep said...
    what i want is exactly u have,
    i want to know how to run your code to get .class file to use in my page

    i am getting some errors.
    dhileep said...
    Thanks a lot for your code.
    I am very happy now. Your code is working :)
    Anonymous said...
    We've made an application allowing to upload file(s) from Android to any web server. It should work with your PHP script. See BucketUpload:
    Upload application for Android

    Anonymous said...
    i'm having a problem with paths here. where do u store ur files on ur phone?

    Shimul said...
    i think the file was saved in where the application resides
    Arnaud said...
    Does it work with a text file? Because I can't upload a simple xml file.
    Nothing is loaded on my server...really strange
    arnaud.farine AROBAS
    Shimul said...
    It was a code of long time ago, i am not familiar with current android sdk, so i am not sure if it will work
    Mudit Agarwal said...

    what is the size limit on the file you are uploading..coz i tried it for larger images and files and i am getting "OutOfMemory" Exception..

    PM me @
    siva said...
    i have copied the code to myapplication to upload the file for the android development,but it shows me a ERROR- can you fix and tel me how to use it..
    siva said...
    this code it stil shows me a ERROR can u tell me how to upload the files using the ANDROID ENVIRONMENT.

    richa said...
    This comment has been removed by the author.
    Andrew Sotzing said...
    Your post and sample code were extremely helpful to me. Have been slaving over this all night/day!

    Thanks much!
    Niklas said...
    not working at all.
    Jake Beasley said...
    Wow, saved me a lot of time!
    Umar said...
    could you please upload complete code here.

    actually i am getting following file path and getting file not found exception
    absolute path="/content:/media/external/images/media/2"

    could you please help me out why i am getting this?
    Umar said...
    This comment has been removed by the author.
    Umar said...
    This comment has been removed by the author.
    Umar said...
    how to add parameters in it its incomplete
    please post complete code.
    jana said...
    Thanks for the code!
    I tried uploading mp3 file
    i got java.lang.OutOfMemoryError.
    plz help me with this.
    Ian said...
    I'm wondering, can i send other information at the same time... i.e. $_POST['action'].... ???
    Dewr said...
    I'm wondering too, can you send other information at the same time... i.e. $_POST['action'].... ???
    Dewr said...
    Oh. I found a way to post other informations! urlString=urlString+"?key=value"+"&key2=value2"+"&key3=value3"+"&key4=value4"...;
    Dewr said...
    failed to send files. now I am referencing this trustful text ->
    Dewr said...
    urlString=urlString+"?key=value"+"&key2=value2"+"&key3=value3"+"&key4=value4"...; //this code will work well!
    Murali said...
    i have error in import org.apache.commons.codec.binary.Base64; and InterfaceHttpUtil ifPostBack; as 'cannot be resolved type'. and please help me. how to convert in android.
    murali-ma said...
    i have error in import org.apache.commons.codec.binary.Base64; and InterfaceHttpUtil ifPostBack; as 'cannot resolved type'. and please help how to convert it in android.
    pokershark103 said...
    Code is working, I tested it with php forms
    pokershark103 said...
    rajesh said...
    hey,thnx fr this 1 prob is code is working propery through wifi bt it's creating prob in GPRS .
    Tinker said...
    if i want to call a jsp code in place of php what will be the code can you provide it ... thanks in advance
    Ecommerce Web Developers said...
    I think most of the peoples are getting good knowledge about android. because your explanation is good and its the useful information, so thanks for providing this great knowledge.

    Android app developer
    Arvesh said...
    Thank you very much for that ! and u know what its because of people like u that am gonna start posting things to help others too !
    Glen Pinheiro said...
    interesting article, please check out my blog,
    swapslove15 said...
    i want ur xml file also to understand it,,,so pls send or copy pest ur whole xml code of this file pls,,,so i understand whats ur design
    Shiwani Malhotra said...
    Fahimshakir Freelancer Developer from Delhi-India,You can provide me part time work for Home,Part Time Developer/Freelancer For PHP , WordPress, Magento, Opencart, Shopify, Codeigniter, Website Maintenance in Delhi -india,
    Ankit Das said...
    Rohan said...
    Hi, I am trying to send an image that is shared from other app (say whatsapp) into server. I am getting the image as Uri type. how can i send this Uri of image to php server.?Please help. I am new to android.
    Rohan said...
    The image shared from other app is received by the function below.

    void handleSendImage(Intent intent) {
    Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM);

    I want to send image of this imageUri to phpserver from my android app.

Post a Comment