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 java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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 ){
try{
connectURL = new URL(urlString);
}catch(Exception ex){
Log.i("URL FORMATION","MALFORMATED URL");
}
this.params = params+"=";
this.fileName = fileName;

}


void doStart(FileInputStream stream){
fileInputStream = stream;
thirdTry();
}

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

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

Log.e(Tag,"Starting to bad things");
// 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=\"uploadedfile\";filename=\"" + exsistingFileName +"\"" + 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);
}

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

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

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

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, "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("http://11.0.6.23/test2.php","noparamshere", NAME_OF_FILE);
htfu.doStart(fis);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}



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 www.anddev.org for more and more tutorials. Thanks for reading my bad post :)

37 Comments:

  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 dhileepen@gmail.com
    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

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

    thanks!
    todd
    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 gmail.com
    Shimul said...
    @Arnaud
    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...
    @Shimul
    hi..

    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 @ mudit.agar@gmail.com
    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..
    Thanks
    siva said...
    this code it stil shows me a ERROR can u tell me how to upload the files using the ANDROID ENVIRONMENT.


    Thanks
    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...
    Hi,
    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 ->
    http://stackoverflow.com/questions/3360957/how-use-multipart-form-data-upload-picture-image-on-android
    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 tutorial...bt 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, http://code-clues.blogspot.in/

Post a Comment