Android upload image


If your application allows the user to upload images to your remote web server, this Android tip is useful to you. In this tip, I am going to show you how to achieve this goal using HttpClient.



HttpClient executes an HttpPost instance to make a post request to the remote server. With the HttpPost instance, you can specify a server side script file (e.g. PHP) to receive the image data and upload it the server. The image data is read from a source image file in your sdcard. Then, the image data is encapsulated in InputStreamBody instance. With the InputStreamBody instance, you specify the image data and name of the image file to be stored on the server. To be ready to upload the image file to the server, you need to attach the InputStreamBody object to a MultipartEntityBuilder instance. The MultipartEntityBuilder instance must be set to the HttpPost instance before you call the execute() method of the HttpClient instance to start upload the image. To use the InputStreamBody and MultipartEntityBuilder classes, you need to add two jar files of Apache Commons libraries: httpcomponents-client-4.3.6 and httpcomponents-core-4.4 to the libs folder of your Android project. These libraries can be downloaded from https://hc.apache.org/downloads.cgi link.
Now to have an example application on uploading image to a remove server, you create a new Android project. Then add a TextView to the activity_main.xml file. It is used to display resulting message of the upload task.



<LinearLayout xmlns:android=" http://schemas.android.com/apk/res/android"
   xmlns:tools=" http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context="com.example.inputdialog.MainActivity" >
  
<TextView
android:id="@+id/txtview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:layout_gravity="center"

/>

</LinearLayout>



In your remote server, you create a PHP file called andupload.php to receive the image file and upload it to the server. In my case, the file is placed in the root folder of my server (http://www.worldbestlearningcenter.com/andupload.php).


<?php
   $target_path="./".basename( $_FILES['img_file']['name']);
   if(file_exists($target_path)) $f=unlink($target_path);
   if(move_uploaded_file($_FILES['img_file']['tmp_name'], $target_path)) {
     echo "ok";
   } else {
     echo "failed";
   }
?>

Here is the code in the MainActivity class that uploads an image file called Rose.jpg in sdcard to the server.


import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

public class MainActivity extends Activity{

   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
  
     BackTask bt=new BackTask();
     bt.execute();
    
   }
  
  
   private class BackTask extends AsyncTask<Void,Void,String>{
   TextView tv;
   protected void onPreExecute(){
      tv=(TextView)findViewById(R.id.txtview);
      tv.setText("Uploading the image. Please wait...");
     }
   protected String doInBackground(Void...params){
   String text="";
     
     try{
     // Create HttpClitent instance
          HttpClient httpClient = new DefaultHttpClient();
          // Create HttpPost instance with specifying php file on server to handle file uploading
          HttpPost httpPostRequest = new HttpPost("http://www.worldbestlearningcenter.com/andupload.php");
         
  
          // Read image file and convert it to byte array
          Bitmap bitmap=BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+"/Rose.jpg");
          ByteArrayOutputStream bo=new ByteArrayOutputStream();
          bitmap.compress(Bitmap.CompressFormat.PNG, 100, bo);
          byte[] data=bo.toByteArray();
          // Specify HttpClient parameters
          httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, System.getProperty("http.agent"));
          // Create InputStreamBody instance with specifying image data destination file name
          InputStreamBody inputStreamBody = new InputStreamBody(new ByteArrayInputStream(data), "/index_files/Rose.jpg");
           // Create MultipartEntityBuilder instance
           MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
           // Set multi-part mode
           multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
           // Attach image data in InputStreamBody instance to MultipartEntityBuilder instance
           multipartEntity.addPart("img_file", inputStreamBody);
           // Set MultipartEntityBuilder instance to HttpPost
           httpPostRequest.setEntity(multipartEntity.build());
    
  // Start uploading the image and get the result from remote server
           ResponseHandler<String> responseHandler = new BasicResponseHandler();        
           text=httpClient.execute(httpPostRequest, responseHandler);
           return text;
          }catch(Exception e){e.printStackTrace();}
     return null;
   }
   protected void onPostExecute(String result){
   if(result.contains("ok"))
   tv.setText("The image was uploaded successfully.");
   else
   tv.setText("Failed to upload the image");
   }
   }
  

}


Before running the example application, do not forget to add the INTERNET permission to the AndroidManifest.xml file of your project.


Android-upload-image

Posted by: Dara | post date: 12-25-2014 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.