Upload Files to Web Server

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

FINAL ANSWER

Postby keatonkeaton999 » Wed Mar 02, 2011 7:20 am

I spent too long on this to not share my final working solution with everyone on here. This code is all based on previous posts. However, no matter how many times people said "I have the working code" they always had some issue in their implementation that made the code not work. This is my final working JAVA and PHP code to upload a file from the Android's SD card to my own Web Server.

The Java/Android Code:

Code: Select all
private void doFileUpload(){
            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            DataInputStream inStream = null;
            String existingFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mypic.png";
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary =  "*****";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1*1024*1024;
            String responseFromServer = "";
            String urlString = "http://mywebsite.com/directory/upload.php";
            try
            {
             //------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(existingFileName) );
             // 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=\"" + existingFileName + "\"" + lineEnd);
             dos.writeBytes(lineEnd);
             // 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("Debug","File is written");
             fileInputStream.close();
             dos.flush();
             dos.close();
            }
            catch (MalformedURLException ex)
            {
                 Log.e("Debug", "error: " + ex.getMessage(), ex);
            }
            catch (IOException ioe)
            {
                 Log.e("Debug", "error: " + ioe.getMessage(), ioe);
            }
            //------------------ read the SERVER RESPONSE
            try {
                  inStream = new DataInputStream ( conn.getInputStream() );
                  String str;
                 
                  while (( str = inStream.readLine()) != null)
                  {
                       Log.e("Debug","Server Response "+str);
                  }
                  inStream.close();

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


The associated PHP code to go on your server (upload.php):
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";
   chmod ("uploads/".basename( $_FILES['uploadedfile']['name']), 0644);
} else{
    echo "There was an error uploading the file, please try again!";
   echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
   echo "target_path: " .$target_path;
}
?>


Things to note.
1) I had "mypic.png" within the root directory of the SD card. As in, if you looked at the Android device through Mass Storage USB view you would put the file in the first directory you come across.
2) USB MASS STORAGE MUST BE TURNED OFF ON THE PHONE! Or just completely unplug it from the computer you are writing the code on to assure this is the case.
3) I had to create an "uploads" folder in the same directory as my php file.
4) You obviously must change the web address I have written as http://mywebsite.com/directory/upload.php to be your own website.

The major changes here that took me so long to figure out where the following.

1) In the android code, a String which contained quotes within quotes (i.e. quotes within strings) was not properly formatted. I think that may be a problem within how this forum works, because I can't imagine everyone made the same mistake over and over. So to be very very clear in case mine messes up when I post on this board too. In the Java code. the line which contains the text "Content-Disposition" must look like this:
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName + "\"" + lineEnd);
And similarly the line which says "String LineEnd" must look like this:
String lineEnd = "\r\n";
(This is the part that caught me up the most)

2) In the PHP code, I chmod the file which is uploaded so it has proper permissions to be viewed.

I hope this all helps.
keatonkeaton999
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Mar 02, 2011 7:02 am

Top

Re: FINAL ANSWER

Postby emmy » Fri Mar 18, 2011 12:49 am

I'm currently trying to upload files with the help of a web server and php. I've tried my index.html file and managed to upload the image either through desktops or phone's browser but not through webView in my app. Problem being that i was unable to select the file to upload.

Can't seem to work my way round though i've followed through previous tutorials. Can anyone tell me where should i call the doFileUpload()?

Would appreciate if anyone would be able to help or give instructions as i'm still quite new in this. :)
emmy
Once Poster
Once Poster
 
Posts: 1
Joined: Sun Oct 03, 2010 12:18 pm

Re: Upload Files to Web Server

Postby volksgrenadier » Mon Mar 28, 2011 3:01 pm

I am trying to capture a photo from the camera and upload it to my server. The following code works flawlessly from my emulator but not from my phone. Any help would be appreciated.

This is the activity code that calls the http upload class :-
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.geocoder;
  2.  
  3. import java.io.File;
  4. import java.util.List;
  5.  
  6.  
  7.  
  8. import android.app.Activity;
  9. import android.content.Context;
  10. import android.content.Intent;
  11. import android.graphics.Bitmap;
  12. import android.location.Location;
  13. import android.location.LocationManager;
  14. import android.net.Uri;
  15. import android.os.Bundle;
  16. import android.os.Environment;
  17. import android.provider.MediaStore;
  18. import android.util.Log;
  19. import android.view.View;
  20. import android.view.View.OnClickListener;
  21. import android.widget.Button;
  22. import android.widget.EditText;
  23. import android.widget.Toast;
  24.  
  25. public class ActivityGeocode extends Activity implements OnClickListener{
  26.     /** Called when the activity is first created. */
  27.         EditText name;
  28.         EditText address;
  29.         EditText comment;
  30.         Bitmap b=null;
  31.         private static Uri _outputFileUri;
  32.         private static File _file;
  33.     @Override
  34.     public void onCreate(Bundle savedInstanceState) {
  35.         super.onCreate(savedInstanceState);
  36.         setContentView(R.layout.main);
  37.          name = (EditText)findViewById(R.id.name);
  38.          address =(EditText)findViewById(R.id.address);
  39.        comment = (EditText)findViewById(R.id.comment);
  40.         Button submit = (Button)findViewById(R.id.submit);
  41.         submit.setOnClickListener(this);
  42.         Button clear = (Button)findViewById(R.id.clear);
  43.         clear.setOnClickListener(this);
  44.         Button photo = (Button)findViewById(R.id.photo);
  45.         photo.setOnClickListener(this);
  46.     }
  47.  
  48.         @Override
  49.         public void onClick(View v)
  50.         {
  51.                 switch(v.getId())
  52.                 {
  53.                 case R.id.submit:
  54.                                 Api obj = new Api();
  55.                                 LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);    
  56.                         List<String> providers = lm.getProviders(true);  
  57.                      
  58.                         /* Loop over the array backwards, and if you get an accurate location, then break out the loop*/  
  59.                         Location l = null;  
  60.                          
  61.                         for (int i=providers.size()-1; i>=0; i--) {  
  62.                            l = lm.getLastKnownLocation(providers.get(i));  
  63.                            if (l != null) break;  
  64.                        }  
  65.                          
  66.                        double lat=0;
  67.                        double lon=0;
  68.                        if (l != null)
  69.                        {  
  70.                            lat = l.getLatitude();  
  71.                            lon = l.getLongitude();  
  72.                          
  73.                        }
  74.                        String url = getString(R.string.url);
  75.                        if (name.length()!=0 && address.length()!=0)
  76.                        {
  77.                            String n = name.getText().toString().trim();
  78.                            n=n.replaceAll(" ", "_");
  79.                            url+="&name="+n;
  80.                            String a = address.getText().toString().trim();
  81.                            a=a.replaceAll(" ", "_");
  82.                            
  83.                            url+="&address="+a;
  84.                            url+="&long="+lat;
  85.                            url+="&lat="+lon;
  86.                            String c = comment.getText().toString().trim();
  87.                            c=c.replaceAll(" ", "_");
  88.                            url+="&comm="+c;
  89.                            
  90.                          
  91.                        }
  92.                        String data = obj.httpGet(url);
  93.                        Log.i("resp",data);
  94.                        Toast.makeText(getBaseContext(), data, Toast.LENGTH_LONG).show();
  95.                        
  96.                        HTTPuploader uobj = new HTTPuploader();
  97.                        Imageupload iobj = new Imageupload();
  98.                        if(b!=null)
  99.                        {
  100.                        int i = uobj.upload(b);
  101.                        //iobj.doFileUpload(_outputFileUri.toString() , _outputFileUri);
  102.                        if (i==1)
  103.                        {
  104.                            Toast.makeText(getBaseContext(), "image upload successful", Toast.LENGTH_LONG).show();
  105.                            
  106.                        }
  107.                        else
  108.                        {
  109.                            Toast.makeText(getBaseContext(), "image upload fail", Toast.LENGTH_LONG).show();
  110.                        }
  111.                        }
  112.                        
  113.                            
  114.                                        
  115.                         break;
  116.                 case R.id.clear:
  117.                         name.setText("");
  118.                         address.setText("");
  119.                         comment.setText("");
  120.                 break;
  121.                 case R.id.photo:
  122.                         Intent _intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);          
  123.  
  124.                  _file = new File(Environment.getExternalStorageDirectory(),"re.jpg");
  125.  
  126.                  _outputFileUri = Uri.fromFile(_file);
  127.  
  128.                  _intent.putExtra(MediaStore.EXTRA_OUTPUT, _outputFileUri);
  129.                  startActivityForResult(_intent, 0);
  130.                
  131.                  
  132.                  
  133.                        
  134.                 }
  135.         }
  136.         @Override
  137.         protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  138.             super.onActivityResult(requestCode, resultCode, data);
  139.  
  140.             if (resultCode == RESULT_CANCELED) {
  141.                 Toast.makeText(this, "Activity cancelled", Toast.LENGTH_LONG).show();
  142.                 return;
  143.             }
  144.  
  145.            
  146.  
  147.                
  148.  
  149.                     if (resultCode == RESULT_OK) {
  150.  
  151.                         try{
  152.                             b = MediaStore.Images.Media.getBitmap(getContentResolver(), _outputFileUri);
  153.                            
  154.                         }
  155.                         catch(Exception e){
  156.                             e.printStackTrace();
  157.                         }
  158.                    
  159.                    
  160.             }
  161.         }
  162. }
Parsed in 0.052 seconds, using GeSHi 1.0.8.4


This is the http upload code which uses POST :-
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.geocoder;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.InputStream;
  5. import java.util.ArrayList;
  6.  
  7. import org.apache.http.HttpEntity;
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.NameValuePair;
  10. import org.apache.http.client.HttpClient;
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.impl.client.DefaultHttpClient;
  14. import org.apache.http.message.BasicNameValuePair;
  15. import org.apache.http.params.CoreProtocolPNames;
  16.  
  17. import android.graphics.Bitmap;
  18.  
  19. import android.util.Log;
  20.  
  21. public class HTTPuploader {
  22.         InputStream is;
  23.         ActivityGeocode obj = new ActivityGeocode();
  24.         public int upload (Bitmap img){
  25.  
  26.         Bitmap bitmapOrg = img;
  27.         ByteArrayOutputStream bao = new ByteArrayOutputStream();
  28.         bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
  29.         byte [] ba = bao.toByteArray();
  30.         String ba1=Base64.encodeBytes(ba);
  31.         ArrayList<NameValuePair> nameValuePairs = new
  32.         ArrayList<NameValuePair>();
  33.         nameValuePairs.add(new BasicNameValuePair("image",ba1));
  34.         try{
  35.         HttpClient httpclient = new DefaultHttpClient();
  36.         String url=null;
  37.         url="http://12.152.53.7/geocoder/upload.php";
  38.         HttpPost httppost = new
  39.         HttpPost(url);
  40.         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
  41.         httppost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);
  42.         HttpResponse response = httpclient.execute(httppost);
  43.         HttpEntity entity = response.getEntity();
  44.         is = entity.getContent();
  45.         Log.i("response", entity.getContent().toString());
  46.         return 1;
  47.         }catch(Exception e){
  48.         Log.e("log_tag", "Error in http connection "+e.toString());
  49.         return 0;
  50.         }
  51.         }
  52.         }
Parsed in 0.037 seconds, using GeSHi 1.0.8.4

And this is my server side code that handles the POST request :-
Syntax: [ Download ] [ Hide ]
Using php Syntax Highlighting
  1. <?php
  2. $base=$_REQUEST['image'];
  3. echo $base;
  4. // base64 encoded utf-8 string
  5. $binary=base64_decode($base);
  6. // binary, utf-8 bytes
  7. $name=md5(date("y-m-d").time());
  8. header('Content-Type: bitmap; charset=utf-8');
  9. // print($binary);
  10. //$theFile = base64_decode($image_data);
  11. $file = fopen('/home/shreyas/geocoder/server/images/'.$name.'.jpg', 'a');
  12. fwrite($file, $binary);
  13. fclose($file);
  14. echo '<img src=test.jpg>';
  15. ?>
Parsed in 0.063 seconds, using GeSHi 1.0.8.4


Any help would be appreciated. I have tried almost all solutions on this thread with no success, the above snipped is the only thing that works on my emulator.

update :- the code does post the image to the server, but it crashes after one use.
volksgrenadier
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Mar 28, 2011 2:13 pm

Re: Upload Files to Web Server

Postby henriquesv » Fri Jul 15, 2011 2:13 am

Hi volksgrenadier,

Did you managed to solve this problem?

Thanks!

Henrique
henriquesv
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Jul 15, 2011 2:01 am

Re: Upload Files to Web Server

Postby stealthcopter » Sun Jul 24, 2011 11:36 pm

keatonkeaton999's code works perfectly for me, thanks!
stealthcopter
Junior Developer
Junior Developer
 
Posts: 12
Joined: Sun Jan 17, 2010 11:42 am

Re: Upload Files to Web Server

Postby breakenter » Mon Jun 18, 2012 10:18 am

breakenter
Freshman
Freshman
 
Posts: 2
Joined: Sun Jun 17, 2012 9:23 am

Top

Re: Upload Files to Web Server

Postby miguegit » Wed Oct 10, 2012 11:24 am

I did all the steps but in the php code I'm always getting this error response:

Notice: Undefined index: uploadedfile in E:\kunden\homepages\16\d434177039\www\sube_imagen\imagen.php on line 19

Notice: Undefined index: uploadedfile in E:\kunden\homepages\16\d434177039\www\sube_imagen\imagen.php on line 22
There was an error uploading the file, please try again!
Notice: Undefined index: uploadedfile in E:\kunden\homepages\16\d434177039\www\sube_imagen\imagen.php on line 28
filename: target_path: uploads/

Does anybody why?
miguegit
Once Poster
Once Poster
 
Posts: 1
Joined: Wed Oct 10, 2012 11:22 am

Re: Upload Files to Web Server

Postby David12 » Mon May 27, 2013 2:00 pm

Branded PC Nehru Place This post is very simple to explain and appreciate without leaving any details out. Great work!
David12
Freshman
Freshman
 
Posts: 5
Joined: Fri Mar 22, 2013 10:14 am

Top
Previous

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 6 guests