Upload Files to Web Server

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

progress bar

Postby Boiler » Mon Nov 09, 2009 11:42 pm

Can anyone show example with progress bar of transfer data ?
Boiler
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Nov 09, 2009 11:35 pm

Top

Postby aswani » Sat Apr 17, 2010 5:23 am

hi all,


store image to server .client side code is ok and here i found server side is php.i am using the sqlserver db and .net at server side.if you have any idea about how to write server side code in asp.net can you please help me


Thanks in advance

Aswan
aswani
Junior Developer
Junior Developer
 
Posts: 19
Joined: Tue Feb 09, 2010 12:41 pm

Re: java.io.FileNotFoundException

Postby Sambo » Mon May 17, 2010 12:57 am

sng2392 wrote:Does anyone have an idea to why I get this error?

10-19 23:02:06.141: ERROR/MediaPlayer(899): error: http://www.webhostsomewhere.com/SomeFolder/upload.aspx
10-19 23:02:06.141: ERROR/MediaPlayer(899): java.io.FileNotFoundException: http://www.webhostsomewhere.com/SomeFolder/upload.aspx
10-19 23:02:06.141: ERROR/MediaPlayer(899): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1064)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at com.vtind.guesswho.ImageDownload.uploadFile(ImageDownload.java:217)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at com.vtind.guesswho.SendView$2.onClick(SendView.java:85)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.view.View.performClick(View.java:2179)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.view.View.onTouchEvent(View.java:3828)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.widget.TextView.onTouchEvent(TextView.java:6291)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.view.View.dispatchTouchEvent(View.java:3368)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:863)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:863)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:863)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:863)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent(PhoneWindow.java:1707)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent(PhoneWindow.java:1197)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.app.Activity.dispatchTouchEvent(Activity.java:1993)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1691)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.view.ViewRoot.handleMessage(ViewRoot.java:1525)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.os.Handler.dispatchMessage(Handler.java:99)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.os.Looper.loop(Looper.java:123)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at android.app.ActivityThread.main(ActivityThread.java:3948)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at java.lang.reflect.Method.invokeNative(Native Method)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at java.lang.reflect.Method.invoke(Method.java:521)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:782)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:540)
10-19 23:02:06.141: ERROR/MediaPlayer(899): at dalvik.system.NativeStart.main(Native Method)

My client side code is identical to what has been posted by jhoffman



I receiving the same error but only when I am not on a WiFi connection. When I am on a decent WiFi connection the file uploads fine using the php script. The file is written just the response from the server is fail, on the non-wifi connection. Any suggestions?
Sambo
Junior Developer
Junior Developer
 
Posts: 14
Joined: Mon May 17, 2010 12:49 am
Location: Seattle, WA

Re: Upload Files to Web Server

Postby Sambo » Tue May 18, 2010 8:07 am

A follow up on my last post, the uploads are failing when I am connected via the T-Mobile Edge network but uploads successfully while on 3G or a wifi connection. I noticed a few other apps unable to upload as well while on the Edge network so I am thinking this issue has to do with Tmobile Edge and not the code.
Sambo
Junior Developer
Junior Developer
 
Posts: 14
Joined: Mon May 17, 2010 12:49 am
Location: Seattle, WA

Re: Upload Files to Web Server

Postby BadGuy » Sat May 22, 2010 12:23 pm

Hi guys, i would like some help here

I have the following php web service:
Syntax: [ Download ] [ Hide ]
Using php Syntax Highlighting
  1. <?php
  2.         session_start();
  3.         include("nusoap.php");
  4.         require 'database.php';
  5.         $srv = new soap_server();
  6.  
  7.         $srv->register("insertMarker");
  8.         function insertMarker($facebookUid, $title, $description, $markerType, $photoPath, $latitude, $longitude)
  9.         {
  10.                
  11.                 $_SESSION["facebookUid"] = $facebookUid;
  12.  
  13.                 if(!file_exists("photos/".$facebookUid)) {
  14.                     mkdir("photos/".$facebookUid, 0777);
  15.                 }
  16.  
  17.                 global $mysqli;
  18.  
  19.                 $query = "INSERT into Markers(id,facebookUid, title, description, markerType, photoPath, latitude, longitude) VALUES('','$facebookUid','$title', '$description', '$markerType', '$photoPath', '$latitude', '$longitude')";
  20.  
  21.                 $result = $mysqli->query($query) or die (mysqli_error($mysqli));
  22.                 mysqli_close($mysqli);
  23.                 if($result) {
  24.                     return 'Successful insertion ';
  25.                 }
  26.                 else {
  27.                     return 'Something went wrong';
  28.                 }
  29.  
  30.         }
  31.         $HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : "";
  32.         $srv->service($HTTP_RAW_POST_DATA);
  33. ?>
Parsed in 0.059 seconds, using GeSHi 1.0.8.4


which I am accessing from android using the soap protocol with the following code
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                   SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
  2.                   //SoapObject
  3.                  request.addProperty("facebookUid", data[0].get(0));
  4.                  request.addProperty("title", data[0].get(1));
  5.                  request.addProperty("description", data[0].get(2));
  6.                  request.addProperty("markerType", data[0].get(3));
  7.                  request.addProperty("photoPath", data[0].get(4));
  8.                  request.addProperty("latitude",data[0].get(5));
  9.                  request.addProperty("longitude", data[0].get(6));
  10.                  
  11.                  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  12.                  envelope.setOutputSoapObject(request);
  13.        
  14.                  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
  15.                  try
  16.                  {
  17.                      androidHttpTransport.call(SOAP_ACTION, envelope);
  18.                      resultsRequestSOAP = envelope.getResponse();
  19.                      String result = (String) resultsRequestSOAP;
  20.                  }
  21.                  catch (Exception aE)
  22.                  {
  23.                   aE.printStackTrace ();;
  24.                  }
  25.  
Parsed in 0.037 seconds, using GeSHi 1.0.8.4


Then I am trying to upload a file to the web server from android. The php code for this is
Syntax: [ Download ] [ Hide ]
Using php Syntax Highlighting
  1. <?php
  2.         session_start();
  3.         $target_path = "photos/".$_SESSION["facebookUid"].'/';
  4.     $target_path = $target_path.basename($_FILES['uploadedfile']['name']);
  5.  
  6.     if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
  7.  
  8.         echo "The file ".basename($_FILES['uploadedfile']['name'])." has been uploaded to the folder ". $target_path;
  9.     }
  10.     else {
  11.  
  12.         echo "There was an error uploading the file, please try again!";
  13.     }
  14. ?>
  15.  
Parsed in 0.064 seconds, using GeSHi 1.0.8.4


and the java code is
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1.                 HttpURLConnection connection = null;
  2.                 DataOutputStream outStream = null;
  3.                 DataInputStream inStream = null;
  4.        
  5.                 String lineEnd = "\r\n";
  6.                 String twoHyphens = "--";
  7.                 String boundary = "*****";
  8.        
  9.                 int bytesRead, bytesAvailable, bufferSize;
  10.        
  11.                 byte[] buffer;
  12.        
  13.                 int maxBufferSize = 1*1024*1024;
  14.        
  15.                 String urlString = "http://192.168.1.2/soap/uploadPhoto.php";
  16.                
  17.                 try {
  18.        
  19.                     FileInputStream fileInputStream = new FileInputStream(new File(photoPath));
  20.        
  21.                     // open a URL connection to the Servlet
  22.                     URL url = new URL(urlString);
  23.        
  24.                     // Open a HTTP connection to the URL
  25.                     connection = (HttpURLConnection) url.openConnection();
  26.        
  27.                     // Allow Inputs
  28.                     connection.setDoInput(true);
  29.        
  30.                     // Allow Outputs
  31.                     connection.setDoOutput(true);
  32.        
  33.                     // Don't use a cached copy.
  34.                     connection.setUseCaches(false);
  35.        
  36.                     // Use a post method.
  37.                     connection.setRequestMethod("POST");
  38.        
  39.                     connection.setRequestProperty("Connection", "Keep-Alive");
  40.                  
  41.                     connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
  42.        
  43.                     outStream = new DataOutputStream(connection.getOutputStream());
  44.        
  45.                     outStream.writeBytes(twoHyphens + boundary + lineEnd);
  46.                     outStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + photoPath +"\"" + lineEnd);
  47.                     outStream.writeBytes(lineEnd);
  48.        
  49.                     // create a buffer of maximum size
  50.                     bytesAvailable = fileInputStream.available();
  51.                     bufferSize = Math.min(bytesAvailable, maxBufferSize);
  52.                     buffer = new byte[bufferSize];
  53.        
  54.                     // read file and write it into form...
  55.        
  56.                     bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  57.                    
  58.                         while (bytesRead > 0) {
  59.                                 outStream.write(buffer, 0, bufferSize);
  60.                         bytesAvailable = fileInputStream.available();
  61.                         bufferSize = Math.min(bytesAvailable, maxBufferSize);
  62.                         bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  63.                     }
  64.        
  65.                     // send multipart form data necesssary after file data...
  66.                         outStream.writeBytes(lineEnd);
  67.                         outStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
  68.        
  69.                     // close streams
  70.                     fileInputStream.close();
  71.                     outStream.flush();
  72.                     outStream.close();
  73.        
  74.                   }
  75.                   catch (MalformedURLException ex) {
  76.                           ex.printStackTrace();
  77.                   }
  78.        
  79.                   catch (IOException ioe) {
  80.                           ioe.printStackTrace();
  81.                   }
  82.        
  83.                   //------------------ read the SERVER RESPONSE
  84.                   try {
  85.                            inStream = new DataInputStream( connection.getInputStream() );
  86.                            String str;
  87.                            
  88.                            while (( str = inStream.readLine()) != null)
  89.                            {
  90.                                    Log.e("Upload photo","Server Response"+str);
  91.                            }
  92.                            inStream.close();
  93.        
  94.                   }
  95.                   catch (IOException ioex){
  96.                           ioex.printStackTrace();
  97.                   }
  98.  
Parsed in 0.048 seconds, using GeSHi 1.0.8.4


Everything works fine except from one thing. In my second php file the variable $_SESSION["facebookUid"] is null. I have tried many things but I can't figure out what the problem is. Does anyone have any idea? Any help would be appreciated! Sorry for my English but they are not very good...
BadGuy
Freshman
Freshman
 
Posts: 4
Joined: Thu May 13, 2010 10:16 am
Location: Patra

Re: Upload Files to Web Server

Postby aswani » Wed Jun 16, 2010 11:23 am

Hi Badguy

Thank you for your replay .my server side webservices is .net .i need help server side code .net or java is better

i don't know php.
aswani
Junior Developer
Junior Developer
 
Posts: 19
Joined: Tue Feb 09, 2010 12:41 pm

Top

Re: Upload Files to Web Server

Postby pedroteixeira07 » Tue Aug 03, 2010 8:19 am

Is there any tutorial that combines a working version of all this 6 pages of try out's?

I'm so confused... some people this works some other it don't..

I'm trying to send a picture to my server which I have the bitmap.

I've managed to do HTTP Post with NameValuePairs.. but have no ideia how to send a file.. any help?

Thank you
pedroteixeira07
Experienced Developer
Experienced Developer
 
Posts: 74
Joined: Sun Oct 18, 2009 6:06 pm
Location: Funchal

Re: Upload Files to Web Server

Postby pedroteixeira07 » Tue Aug 03, 2010 9:13 am

Ok I'm trying josh way.. I just have this syntax error:

dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + exsistingFileName +""" + lineEnd);

:(
pedroteixeira07
Experienced Developer
Experienced Developer
 
Posts: 74
Joined: Sun Oct 18, 2009 6:06 pm
Location: Funchal

Re:

Postby cmf » Fri Aug 27, 2010 4:22 pm

Hi I am trying to use the code you provided, but still cannot get it works.

the server php is used as you provided
Below is my code:
can somebody help me? Thanks

Code: Select all
package com.test.upload;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class testupload extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        doFileUpload();
    }
   
    private void doFileUpload(){

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

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

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


         int bytesRead, bytesAvailable, bufferSize;

         byte[] buffer;

         int maxBufferSize = 1*1024*1024;

         String responseFromServer = "";

         String urlString = "http://www.myserver.com/testupload.php";


         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("Content-Type", "multipart/form-data;boundary="+boundary);

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

          dos.writeBytes(twoHyphens + boundary + lineEnd);
         // dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + exsistingFileName +""" + lineEnd);
          dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile   \";filename=\""+exsistingFileName +"\"" + lineEnd);
          dos.writeBytes(lineEnd);

          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 (IOException 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 (IOException ioex){
              Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
         }

       }
}





jhoffman wrote:I actually solved my own problem after about a week of agonizing over it, but for any future readers of this thread, here are the two pieces of the puzzle, put together, with me saying that it worked for me:

Java code (as previously posted in this thread -- this is not my work):
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. import java.io.DataInputStream;
  2. import java.io.DataOutputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import java.net.HttpURLConnection;
  7. import java.net.MalformedURLException;
  8. import java.net.URL;
  9.  
  10. import android.app.Activity;
  11. import android.os.Bundle;
  12. import android.util.Log;
  13.  
  14. public class TestUpload extends Activity {
  15.     /** Called when the activity is first created. */
  16.     @Override
  17.     public void onCreate(Bundle savedInstanceState) {
  18.         super.onCreate(savedInstanceState);
  19.         setContentView(R.layout.main);
  20.     }
  21.    
  22.     private void doFileUpload(){
  23.  
  24.           HttpURLConnection conn = null;
  25.           DataOutputStream dos = null;
  26.           DataInputStream inStream = null;
  27.  
  28.          
  29.           String exsistingFileName = "/sdcard/yourfile.jpg";
  30.           // Is this the place are you doing something wrong.
  31.  
  32.           String lineEnd = "rn";
  33.           String twoHyphens = "--";
  34.           String boundary =  "*****";
  35.  
  36.  
  37.           int bytesRead, bytesAvailable, bufferSize;
  38.  
  39.           byte[] buffer;
  40.  
  41.           int maxBufferSize = 1*1024*1024;
  42.  
  43.           String responseFromServer = "";
  44.  
  45.           String urlString = "http://localhost/uploader.php";
  46.  
  47.  
  48.           try
  49.           {
  50.            //------------------ CLIENT REQUEST
  51.          
  52.           Log.e("MediaPlayer","Inside second Method");
  53.  
  54.           FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) );
  55.  
  56.            // open a URL connection to the Servlet
  57.  
  58.            URL url = new URL(urlString);
  59.  
  60.  
  61.            // Open a HTTP connection to the URL
  62.  
  63.            conn = (HttpURLConnection) url.openConnection();
  64.  
  65.            // Allow Inputs
  66.            conn.setDoInput(true);
  67.  
  68.            // Allow Outputs
  69.            conn.setDoOutput(true);
  70.  
  71.            // Don't use a cached copy.
  72.            conn.setUseCaches(false);
  73.  
  74.            // Use a post method.
  75.            conn.setRequestMethod("POST");
  76.  
  77.            conn.setRequestProperty("Connection", "Keep-Alive");
  78.          
  79.            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
  80.  
  81.            dos = new DataOutputStream( conn.getOutputStream() );
  82.  
  83.            dos.writeBytes(twoHyphens + boundary + lineEnd);
  84.            dos.writeBytes("Content-Disposition: form-data; name="uploadedfile";filename="" + exsistingFileName +""" + lineEnd);
  85.            dos.writeBytes(lineEnd);
  86.  
  87.            Log.e("MediaPlayer","Headers are written");
  88.  
  89.            // create a buffer of maximum size
  90.  
  91.            bytesAvailable = fileInputStream.available();
  92.            bufferSize = Math.min(bytesAvailable, maxBufferSize);
  93.            buffer = new byte[bufferSize];
  94.  
  95.            // read file and write it into form...
  96.  
  97.            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  98.  
  99.            while (bytesRead > 0)
  100.            {
  101.             dos.write(buffer, 0, bufferSize);
  102.             bytesAvailable = fileInputStream.available();
  103.             bufferSize = Math.min(bytesAvailable, maxBufferSize);
  104.             bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  105.            }
  106.  
  107.            // send multipart form data necesssary after file data...
  108.  
  109.            dos.writeBytes(lineEnd);
  110.            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
  111.  
  112.            // close streams
  113.            Log.e("MediaPlayer","File is written");
  114.            fileInputStream.close();
  115.            dos.flush();
  116.            dos.close();
  117.  
  118.  
  119.           }
  120.           catch (MalformedURLException ex)
  121.           {
  122.                Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
  123.           }
  124.  
  125.           catch (IOException ioe)
  126.           {
  127.                Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
  128.           }
  129.  
  130.  
  131.           //------------------ read the SERVER RESPONSE
  132.  
  133.  
  134.           try {
  135.                 inStream = new DataInputStream ( conn.getInputStream() );
  136.                 String str;
  137.                
  138.                 while (( str = inStream.readLine()) != null)
  139.                 {
  140.                      Log.e("MediaPlayer","Server Response"+str);
  141.                 }
  142.                 inStream.close();
  143.  
  144.           }
  145.           catch (IOException ioex){
  146.                Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
  147.           }
  148.  
  149.         }
  150. }
  151.  
Parsed in 0.055 seconds, using GeSHi 1.0.8.4

The PHP server-side (again, posted earlier in this thread, and not my work, but these two never appear in one single post saying that they work together):
Code: Select all
<?php
// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path. 
Result is "uploads/filename.extension" */
$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 two things you need to set up in the Java file are: urlString and existingFileName. Configure these such that they match whatever you name your PHP file, and whatever file you're trying to upload. Keep in mind that (as previously posted) you must manually push said file to your emulator's pseudo-SD Card for this to work. (Or have it on a real physical SD card if testing on a real phone). I hope this clears up any confusion that other readers like myself may have in the future!
cmf
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Aug 27, 2010 4:17 pm

Re:

Postby imdumm » Mon Nov 15, 2010 4:49 pm

venkat wrote:Dear Katharnavas. Thanks a lot. it works... :) :D :) :D


Regards, :D
Venkat.. :) :D :)



Sorry..., but I still don't get it...How you guys did it?
i think i have tried same code just like what Katharnavas did...
but in my emulator, it is always show "the application has stop unexpectedly etc..."
what is wrong?

this is my php code====
Code: Select all
<?php
mysql_connect("mysql8.000webhost.com", "a3603099_drikvy","drikvyx86");
mysql_select_db("a3603099_android");

if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);

if(!get_magic_quotes_gpc())
{
    $fileName = addslashes($fileName);
}


$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";

mysql_query($query) or die('Error, query failed');

echo "<br>File $fileName uploaded<br>";
}
?>


i want to upload image file from sdcard or filepath to php-mysql server...
i will appreciate any help
thanks
imdumm
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Nov 15, 2010 4:06 pm

Re: Upload Files to Web Server

Postby joellesba » Tue Nov 16, 2010 1:04 am

I need some help. I have a toggle button on/off, all I want it to do is read on or off on my localhost webpage. I did the internet permission in the manifest and created the button in main.xml, here is my java code, all I want is the webpage to simply read On or Off depending on the button push. I'm begging for help, I read through this forum and tried everything and nothing worked, hence the unused imports... Please help!!!!
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.Menu1;
  2.  
  3. import java.io.IOException;
  4. import java.io.UnsupportedEncodingException;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7.  
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.NameValuePair;
  10. import org.apache.http.client.ClientProtocolException;
  11. import org.apache.http.client.HttpClient;
  12. import org.apache.http.client.ResponseHandler;
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;
  14. import org.apache.http.client.methods.HttpPost;
  15. import org.apache.http.impl.client.BasicResponseHandler;
  16. import org.apache.http.impl.client.DefaultHttpClient;
  17. import org.apache.http.message.BasicNameValuePair;
  18.  
  19. import android.app.Activity;
  20. import android.os.Bundle;
  21. import android.view.View;
  22. import android.widget.Toast;
  23. import android.widget.ToggleButton;
  24.  
  25. public class success extends Activity {
  26.         @Override
  27.         public void onCreate(Bundle savedInstanceState) {
  28.                 super.onCreate(savedInstanceState);
  29.                 setContentView(R.layout.success);
  30.  
  31.                 final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
  32.                 togglebutton.setOnClickListener(new View.OnClickListener() {
  33.                     public void onClick(View v) {
  34.                         // Perform action on clicks
  35.                         if (togglebutton.isChecked()) {
  36.                             Toast.makeText(success.this, "The fuel cell is on", Toast.LENGTH_LONG).show();
  37.                        
  38.                        
  39.                         } else {
  40.                             Toast.makeText(success.this, "The fuel cell is off", Toast.LENGTH_LONG).show();
  41.                    
  42.                        
  43.                         }
  44.                     }
  45.                 });
  46.                
  47.         }
  48.          
  49.                
  50.         }
  51.  
Parsed in 0.042 seconds, using GeSHi 1.0.8.4
joellesba
Freshman
Freshman
 
Posts: 7
Joined: Mon Nov 15, 2010 10:59 pm

Re: Upload Files to Web Server

Postby Efefes » Sun Dec 26, 2010 7:58 pm

Can someone please once more explain how exactly do I get the correct path to files?
I'm using jhoffman's code, but my stuff crashes because it can't find the file. I tried using the file explorer to bring test.png into the phone, I also tried opening a browser and downloading the image from the web.
So I should be having the image in two places. I've tried the following paths:
"test.png" "/sdcard/test.png" "/downloads/test.png" "/sdcard/downloads/test.png" yet none of them works.
The application is also crashing on my phone, but not sure if its for the same reason (no logcat over there)

I'm in a little bit of hurry getting this application to work, so any help is very welcome!
Efefes
Freshman
Freshman
 
Posts: 6
Joined: Thu Dec 09, 2010 2:18 pm

Re: Upload Files to Web Server

Postby Efefes » Sun Dec 26, 2010 8:32 pm

I think i might have figured out the path part, at least the application doesn't crash instantly on my phone anymore after i switched to use this:
String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test2.jpg";

But what the application does is it just opens a black screen with the tesxt Hello World, TestUploader! and nothing else happens. Using a html file to test out my php script works just fine, and my php script is identical to the ones posted here so the problem is client side. I've also added INTERNET permission to the androidmanifest file.

The application still crashes on emulator immediately though for not being able to locate the file.

here's the full code:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package test.android.uploader;
  2.  
  3. import java.io.DataInputStream;
  4. import java.io.DataOutputStream;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. import java.net.HttpURLConnection;
  9. import java.net.MalformedURLException;
  10. import java.net.URL;
  11.  
  12. import android.app.Activity;
  13. import android.os.Bundle;
  14. import android.os.Environment;
  15. import android.util.Log;
  16.  
  17. public class TestUploader extends Activity {
  18.     /** Called when the activity is first created. */
  19.     @Override
  20.     public void onCreate(Bundle savedInstanceState) {
  21.         super.onCreate(savedInstanceState);
  22.         setContentView(R.layout.main);
  23.         doFileUpload();
  24.     }
  25.    
  26.     private void doFileUpload(){
  27.  
  28.           HttpURLConnection conn = null;
  29.           DataOutputStream dos = null;
  30.           DataInputStream inStream = null;
  31.  
  32.          
  33.           String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/test2.jpg";
  34.           // Is this the place are you doing something wrong.
  35.  
  36.           String lineEnd = "rn";
  37.           String twoHyphens = "--";
  38.           String boundary =  "*****";
  39.  
  40.  
  41.           int bytesRead, bytesAvailable, bufferSize;
  42.  
  43.           byte[] buffer;
  44.  
  45.           int maxBufferSize = 1*1024*1024;
  46.  
  47.           String responseFromServer = "";
  48.  
  49.           String urlString = "http://192.168.0.8/test/TestUpload.php";
  50.  
  51.  
  52.           try
  53.           {
  54.            //------------------ CLIENT REQUEST
  55.          
  56.           Log.e("MediaPlayer","Inside second Method");
  57.  
  58.           FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
  59.  
  60.            // open a URL connection to the Servlet
  61.  
  62.            URL url = new URL(urlString);
  63.  
  64.  
  65.            // Open a HTTP connection to the URL
  66.  
  67.            conn = (HttpURLConnection) url.openConnection();
  68.  
  69.            // Allow Inputs
  70.            conn.setDoInput(true);
  71.  
  72.            // Allow Outputs
  73.            conn.setDoOutput(true);
  74.  
  75.            // Don't use a cached copy.
  76.            conn.setUseCaches(false);
  77.  
  78.            // Use a post method.
  79.            conn.setRequestMethod("POST");
  80.  
  81.            conn.setRequestProperty("Connection", "Keep-Alive");
  82.          
  83.            conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
  84.  
  85.            dos = new DataOutputStream( conn.getOutputStream() );
  86.  
  87.            dos.writeBytes(twoHyphens + boundary + lineEnd);
  88.            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd);
  89.            dos.writeBytes(lineEnd);
  90.  
  91.            Log.e("MediaPlayer","Headers are written");
  92.  
  93.            // create a buffer of maximum size
  94.  
  95.            bytesAvailable = fileInputStream.available();
  96.            bufferSize = Math.min(bytesAvailable, maxBufferSize);
  97.            buffer = new byte[bufferSize];
  98.  
  99.            // read file and write it into form...
  100.  
  101.            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  102.  
  103.            while (bytesRead > 0)
  104.            {
  105.             dos.write(buffer, 0, bufferSize);
  106.             bytesAvailable = fileInputStream.available();
  107.             bufferSize = Math.min(bytesAvailable, maxBufferSize);
  108.             bytesRead = fileInputStream.read(buffer, 0, bufferSize);
  109.            }
  110.  
  111.            // send multipart form data necesssary after file data...
  112.  
  113.            dos.writeBytes(lineEnd);
  114.            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
  115.  
  116.            // close streams
  117.            Log.e("MediaPlayer","File is written");
  118.            fileInputStream.close();
  119.            dos.flush();
  120.            dos.close();
  121.  
  122.  
  123.           }
  124.           catch (MalformedURLException ex)
  125.           {
  126.                Log.e("MediaPlayer", "error: " + ex.getMessage(), ex);
  127.           }
  128.  
  129.           catch (IOException ioe)
  130.           {
  131.                Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe);
  132.           }
  133.  
  134.  
  135.           //------------------ read the SERVER RESPONSE
  136.  
  137.  
  138.           try {
  139.                 inStream = new DataInputStream ( conn.getInputStream() );
  140.                 String str;
  141.                
  142.                 while (( str = inStream.readLine()) != null)
  143.                 {
  144.                      Log.e("MediaPlayer","Server Response"+str);
  145.                 }
  146.                 inStream.close();
  147.  
  148.           }
  149.           catch (IOException ioex){
  150.                Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
  151.           }
  152.  
  153.         }
  154. }
  155.  
Parsed in 0.056 seconds, using GeSHi 1.0.8.4
Efefes
Freshman
Freshman
 
Posts: 6
Joined: Thu Dec 09, 2010 2:18 pm

Re: Upload Files to Web Server

Postby androides » Mon Jan 03, 2011 10:18 am

All we have to do on server's side is to create the .php file, put it into htdocs on Apache folder and start Apache Server? Also, create an "upload" folder in Apache folder.

Do I miss anything? It won't work (the code that many of you tried and worked)
androides
Developer
Developer
 
Posts: 35
Joined: Sat Oct 09, 2010 10:22 am

Re: Upload Files to Web Server

Postby androides » Wed Jan 05, 2011 1:58 pm

I tried it with pure java code (in my pc) and it worked.

But when I try to run it in Android phone (HTC Desire) I get the following error:
Code: Select all
01-05 13:40:34.618: ERROR/Got an IOException:(4721): java.net.SocketException: The operation timed out
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at org.apache.harmony.luni.platform.OSNetworkSystem.connectStreamWithTimeoutSocketImpl(Native Method)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at org.apache.harmony.luni.platform.OSNetworkSystem.connect(OSNetworkSystem.java:115)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:244)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:533)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at java.net.Socket.connect(Socket.java:1055)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:62)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:88)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHTTPConnection(HttpURLConnectionImpl.java:927)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:909)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:1253)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at net.Upload.Upload.onCreate(Upload.java:55)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1069)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2751)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2803)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at android.app.ActivityThread.access$2300(ActivityThread.java:135)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2136)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at android.os.Handler.dispatchMessage(Handler.java:99)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at android.os.Looper.loop(Looper.java:144)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at android.app.ActivityThread.main(ActivityThread.java:4937)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at java.lang.reflect.Method.invokeNative(Native Method)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at java.lang.reflect.Method.invoke(Method.java:521)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-05 13:40:34.618: ERROR/Got an IOException:(4721):     at dalvik.system.NativeStart.main(Native Method)


This line is the problem:
Code: Select all
outputStream = new DataOutputStream( connection.getOutputStream() );

it can't get output stream.

Any ideas? Please, I need some help :(
androides
Developer
Developer
 
Posts: 35
Joined: Sat Oct 09, 2010 10:22 am

Top
PreviousNext

Return to Novice Tutorials

Who is online

Users browsing this forum: Yahoo [Bot] and 8 guests