andbook!.pdf - Learning Android Get an anddev.org - Android-Shirt Back to index
anddev.org Header Logo
FAQ Search Top rated articles Browse Feeds anddev.org - Authors Contact Details Register Log in

Upload Files to Web Server

Goto page Previous  1, 2, 3, 4
 
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials
Author Message
raquibulbari
Developer


Joined: 16 Dec 2007
Posts: 25
Location: dhaka,bangladesh

PostPosted: Thu Jan 24, 2008 5:34 pm    Post subject: Reply with quote

Here is the code that worked for me
Java:



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,"Inside second Method");



     // Open a HTTP connection to the URL

       //connectURL is a URL object
     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("Fuck response",s);
     dos.close();


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

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


This code worked for me, php code is same as posted before Very Happy

_________________
Shimugool
Back to top
View user's profile Send private message Visit poster's website
Katharnavas
Senior Developer


Joined: 04 Dec 2007
Posts: 100
Location: India

PostPosted: Fri Jan 25, 2008 5:03 am    Post subject: Reply with quote

raquibulbari wrote:
Katharnavas thanks man , your code came in great help for me, the whole day i was trying to upload image, the code was about to be same like you , at least your code worked, thanks man, i was just getting frustrated on me

Very Happy


Its nice to hear that you got ur problem fixed..
Back to top
View user's profile Send private message Yahoo Messenger
cyberrob
Freshman


Joined: 13 Dec 2007
Posts: 9

PostPosted: Mon Feb 04, 2008 7:48 am    Post subject: Reply with quote

Hey guys, I try codes you post above, Seems everything ok but...

I got a Java.io.FileNotFoundException

I try
Java:
String exsistingFileName = "ning";
fileInputStream = openFileInput(exsistingFileName);

exception happened at line2, the one I assign path to fileInputStream
Same result when I use
Java:
fileInputStream = new FileInputStream(new File(exsistingFileName))


So I'm wondering where should I point the file path to ??
I put the .png file in /res/drawble/
and include it by using getString(R.drawable.abc.png),which also give me the same exception.

Hope someone could help me out here! THX a LOT!
Back to top
View user's profile Send private message
plusminus
Site Admin


Joined: 14 Nov 2007
Posts: 2102
Location: Germany

PostPosted: Mon Feb 04, 2008 10:22 am    Post subject: Reply with quote

Hello cyberrob,

Idea raquibulbari probably had the file manually pushed to the emulator Exclamation
you cannot use getString(R.drawable.abc.png);, because it is only capable of grabbing String-Resources and not the Names of other resources. Also you can not access images you placed under "/res/drawable/xyz.png", by their filenames, because they got compiled into your application.

Regards,
plusminus

_________________

| Android Development Community / Tutorials
Back to top
View user's profile Send private message Send e-mail Visit poster's website
cyberrob
Freshman


Joined: 13 Dec 2007
Posts: 9

PostPosted: Tue Feb 12, 2008 3:33 am    Post subject: Reply with quote

Oh!that's why I cant do it that way,ok! I try manually push file into it. Thanks! Very Happy

plusminus wrote:
Hello cyberrob,

Idea raquibulbari probably had the file manually pushed to the emulator Exclamation
you cannot use getString(R.drawable.abc.png);, because it is only capable of grabbing String-Resources and not the Names of other resources. Also you can not access images you placed under "/res/drawable/xyz.png", by their filenames, because they got compiled into your application.

Regards,
plusminus
Back to top
View user's profile Send private message
cyberrob
Freshman


Joined: 13 Dec 2007
Posts: 9

PostPosted: Thu Feb 14, 2008 9:10 am    Post subject: Reply with quote

Finally I got everything WORK!!
I found posts above miss to assign FileInputStream a value, so I assign the file I wanna upload like this:
Code:
fileInputStream = new FileInputStream(exsistingFileName);


in try-catch block, so it all work out! Laughing
Next Step try to show the php echo msg on "showalert"
Thank you guys!!

plusminus wrote:
Hello cyberrob,

Idea raquibulbari probably had the file manually pushed to the emulator Exclamation
you cannot use getString(R.drawable.abc.png);, because it is only capable of grabbing String-Resources and not the Names of other resources. Also you can not access images you placed under "/res/drawable/xyz.png", by their filenames, because they got compiled into your application.

Regards,
plusminus
Back to top
View user's profile Send private message
inter
Junior Developer


Joined: 21 Feb 2008
Posts: 23

PostPosted: Wed Feb 27, 2008 3:17 pm    Post subject: Reply with quote

php:
<?php
$target_path = "./ploads/";

$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!";
}
?>


I use this code in server side .But it not work .It response "There was an error uploading the side ,please try again!!"

The client side is same above.
Can you help me. Thanks.
Back to top
View user's profile Send private message
inter
Junior Developer


Joined: 21 Feb 2008
Posts: 23

PostPosted: Wed Feb 27, 2008 3:26 pm    Post subject: Reply with quote

I'm sory .I have just done it
Thank a lot!!!!
Back to top
View user's profile Send private message
ekambresh
Junior Developer


Joined: 08 Feb 2008
Posts: 22
Location: Bangalore

PostPosted: Mon Mar 17, 2008 11:31 am    Post subject: wre to place image file,while uploding to server Reply with quote

please tell me wre to plce the image file while uploading to the server....if possible send me the tutorial





tnx
ekambresh

_________________
ekambresh
Back to top
View user's profile Send private message Yahoo Messenger
venkat
Senior Developer


Joined: 27 Nov 2007
Posts: 152
Location: India

PostPosted: Mon Mar 17, 2008 2:39 pm    Post subject: Reply with quote

Hi ekambresh, u can upload images also. please push images manually to files folder using "DDMS" tool .


here how you can push images into "files" folder.

window --> show view --> File Explorer than, navigate to data/data/[your package structre]/files then,

select that folder, then , there is two small phone icons. first one is used to pull files from that folder to your system and another one is used to push files into that folder.

use second icon to push files from your system to "files" folder.

I hope it will help. Smile

_________________
Regards,
Venkat.
Back to top
View user's profile Send private message
rohan
Developer


Joined: 19 Mar 2008
Posts: 28

PostPosted: Wed Mar 19, 2008 2:35 pm    Post subject: path Reply with quote

venkat wrote:
Hi ekambresh, u can upload images also. please push images manually to files folder using "DDMS" tool .


here how you can push images into "files" folder.

window --> show view --> File Explorer than, navigate to data/data/[your package structre]/files then,

select that folder, then , there is two small phone icons. first one is used to pull files from that folder to your system and another one is used to push files into that folder.

use second icon to push files from your system to "files" folder.

I hope it will help. Smile



hi venkat,
I am new to android.
I did not get the path that you have given "window --> show view --> File Explorer than, navigate to data/data/[your package structre]/files" . how do I go to the above path? and also what is "DDMS" tool .

thanx in advance
Back to top
View user's profile Send private message
mehta
Once Poster


Joined: 30 Mar 2008
Posts: 1

PostPosted: Sun Mar 30, 2008 1:45 am    Post subject: Reply with quote

In the examples above, the path of the file to be uploaded is hardcoded. Is there a way to let the user choose the file path dynamically?
Back to top
View user's profile Send private message
marielisacr
Junior Developer


Joined: 21 May 2008
Posts: 12

PostPosted: Mon Jul 14, 2008 2:18 pm    Post subject: Reply with quote

Hi, am trying to upoad a file to a server,

the problem is that I need to send two differents parameters to the server, one is the file and the another is a text.

I am trying this code:

public void doFileUpload(String exsistingFileName, String xml){

HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;


//String exsistingFileName = "/sdcard/img2.jpg";
// Is this the place are you doing something wrong.

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "-----------------------------29772313742745";


int bytesRead, bytesAvailable, bufferSize;

byte[] buffer;

int maxBufferSize = 1*1024*1024;


String responseFromServer = "";

String urlString = Constants.WEB_ADDRESS+"upload.do";


try
{
//------------------ CLIENT REQUEST

Log.e("MediaPlayer","Inside second Method");

FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );

// open a URL connection to the Servlet

URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.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("Cookie", "JSESSIONID="+PlayList.getSessionId());
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

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

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"xml\""+lineEnd+URLEncoder.encode(xml,"UTF-8") + lineEnd);
dos.writeBytes(boundary + lineEnd);
//dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"fileFile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
dos.writeBytes(lineEnd);

Log.e("MediaPlayer","xml ");

Log.e("MediaPlayer","Headers are written");

// create a buffer of maximum size

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// read file and write it into form...

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("MediaPlayer","File is written");
fileInputStream.close();
dos.flush();
dos.close();


}
catch (MalformedURLException ex)
{
Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
}

catch (Exception ioe)
{
Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
}


//------------------ read the SERVER RESPONSE


try {
inStream = new DataInputStream ( conn.getInputStream() );
String str;

while (( str = inStream.readLine()) != null)
{
Log.e("MediaPlayer","Server Response"+str);
}
inStream.close();

}
catch (Exception ioex){
Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
}

}

but it doesn't work, it only recognizes one of the parameters. I got an error on the server's side that the file is null and the text variable had everything, including the file.

I hope someone can help me.

Thanks.
Back to top
View user's profile Send private message
marielisacr
Junior Developer


Joined: 21 May 2008
Posts: 12

PostPosted: Mon Jul 14, 2008 2:20 pm    Post subject: Reply with quote

Sorry, here is the code more clear

Java:
public void doFileUpload(String exsistingFileName, String xml){

          HttpURLConnection conn = null;
          DataOutputStream dos = null;
          DataInputStream inStream = null;


          //String exsistingFileName = "/sdcard/img2.jpg";
          // Is this the place are you doing something wrong.

          String lineEnd = "\r\n";
          String twoHyphens = "--";
          String boundary =  "-----------------------------29772313742745";


          int bytesRead, bytesAvailable, bufferSize;

          byte[] buffer;

          int maxBufferSize = 1*1024*1024;


          String responseFromServer = "";

          String urlString = Constants.WEB_ADDRESS+"upload.do";


          try
          {
               //------------------ CLIENT REQUEST

               Log.e("MediaPlayer","Inside second Method");

               FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );

               // open a URL connection to the Servlet

               URL url = new URL(urlString);
               // Open a HTTP connection to the URL
               conn = (HttpURLConnection) url.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("Cookie", "JSESSIONID="+PlayList.getSessionId());
               conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

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

               dos.writeBytes(twoHyphens + boundary + lineEnd);
               dos.writeBytes("Content-Disposition: form-data; name=\"xml\""+lineEnd+URLEncoder.encode(xml,"UTF-8") + lineEnd);
               dos.writeBytes(boundary + lineEnd);
               //dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
               dos.writeBytes("Content-Disposition: form-data; name=\"fileFile\";filename=\"" + exsistingFileName +"\"" + lineEnd);
               dos.writeBytes(lineEnd);

               Log.e("MediaPlayer","xml ");

               Log.e("MediaPlayer","Headers are written");

               // create a buffer of maximum size

               bytesAvailable = fileInputStream.available();
               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               buffer = new byte[bufferSize];

               // read file and write it into form...

               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("MediaPlayer","File is written");
               fileInputStream.close();
               dos.flush();
               dos.close();


          }
          catch (MalformedURLException ex)
          {
               Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
          }

          catch (Exception ioe)
          {
               Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
          }


          //------------------ read the SERVER RESPONSE


          try {
               inStream = new DataInputStream ( conn.getInputStream() );
               String str;

               while (( str = inStream.readLine()) != null)
               {
                    Log.e("MediaPlayer","Server Response"+str);
               }
               inStream.close();

          }
          catch (Exception ioex){
               Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
          }

     }
Back to top
View user's profile Send private message
Display posts from previous:   
       anddev.org - Android Development Community | Android Tutorials | Index -> Novice Tutorials All times are GMT + 1 Hour
Goto page Previous  1, 2, 3, 4
Page 4 of 4

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
You cannot attach files in this forum
You can download files in this forum


© 2007, Android Development Community
All rights reserved.
Powered by phpBB.