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 :)
Labels: Android, file upload, php server
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
i want to know how to run your code to get .class file to use in my page
i am getting some errors.
I am very happy now. Your code is working :)
Upload application for Android
Cheers.
thanks!
todd
Nothing is loaded on my server...really strange
arnaud.farine AROBAS gmail.com
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
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
Thanks
Thanks
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?
please post complete code.
Thanks for the code!
I tried uploading mp3 file
i got java.lang.OutOfMemoryError.
plz help me with this.
http://stackoverflow.com/questions/3360957/how-use-multipart-form-data-upload-picture-image-on-android
Android app developer
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.
Freelance Writers