Uploading an Image to the Android Studio

Hi all,

In today's tutorial I will show you how to send an image to server using Postal service method in ANDROID.

Uploading an epitome to server is a bones requirement in many of our application.
Sending data to server which is using a PHP Script is already explained in this instance .
Now in this example I will prove yous how to transport an epitome file.

For that start we have to read the file, put information technology in nameValuePairs and then send using HttpPost.

I accept already shown you three other methods on uploading a file to server. If you desire you tin can check these posts.

  • How to Upload Multiple files in one asking along with other string parameters in android?
  • Uploading sound, video or image files from Android to server.
  • How to upload an epitome from Android device to server? – Method 4

These are for downloading files from the server.

  • How to Download an prototype in ANDROID programatically?
  • How to download a file to your android device from a remote server with a custom progressbar showing progress?

if you lot desire to use the android using php and mysql
delight check these posts.

  • Android phpMysql connectedness
  • Android phpmySQL connexion redone.

Make easy money with infolinks

Add Permission

Add "android.permission.Net" permission to your AndroidManifest.xml file.

Note

Yous demand to add the below to your build.gradle since Apache library is deprecated by Google.

android {
useLibrary 'org.apache.http.legacy'
}

build.gradle

Our Sample build.gradle may expect like this.

apply plugin: 'com.android.application'  android {     compileSdkVersion 23     buildToolsVersion "23.0.three"      defaultConfig {         applicationId "com.coderzheaven.uploadimage"         minSdkVersion 21         targetSdkVersion 23         versionCode 1         versionName "1.0"     }     buildTypes {         release {             minifyEnabled fake             proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'         }     } }  android {     useLibrary 'org.apache.http.legacy' }  dependencies {     compile fileTree(dir: 'libs', include: ['*.jar'])     testCompile 'junit:junit:4.12'     compile 'com.android.back up:appcompat-v7:23.2.1'     compile 'com.android.support:design:23.2.1' }        

Layout

Our Sample XML layout will look like this.

<?xml version="1.0" encoding="utf-eight"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-motorcar"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     android:paddingBottom="@dimen/activity_vertical_margin"     android:paddingLeft="@dimen/activity_horizontal_margin"     android:paddingRight="@dimen/activity_horizontal_margin"     android:paddingTop="@dimen/activity_vertical_margin"     app:layout_behavior="@cord/appbar_scrolling_view_behavior"     tools:context="com.coderzheaven.uploadimage.MainActivity"     tools:showIn="@layout/activity_main">      <Button         android:id="@+id/btnSelect"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Select Image" />      <ImageView         android:id="@+id/imgView"         android:layout_width="300dp"         android:layout_height="300dp"         android:layout_gravity="heart" />      <Button         android:id="@+id/btnUpload"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:text="Upload Epitome" />      <TextView         android:id="@+id/txtStatus"         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:layout_marginTop="20dp"         android:gravity="center"         android:text=""         android:textColor="@android:colour/holo_green_light" />  </LinearLayout>        

Make easy money with infolinks

Android Source Lawmaking

We will have a split up form for sending image.

Create a course named "UploadImageApacheHttp" and copy the below contents to it.
Before that, download the Base64 file from here which encodeBytes in Base64 Format.
Add together information technology to your project.

File Upload Utility form

package com.coderzheaven.uploadimage;  import android.graphics.Bitmap; import android.os.Handler; import android.util.Log;  import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.customer.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils;  import java.io.ByteArrayOutputStream; import java.util.ArrayList;  public class UploadImageApacheHttp {      public static terminal Cord TAG = "Upload Image Apache";      public void doFileUpload(terminal String url, final Bitmap bmp, final Handler handler){          Thread t = new Thread(new Runnable() {             @Override             public void run() {                  Log.i(TAG, "Starting Upload...");                 concluding ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();                 nameValuePairs.add(new BasicNameValuePair("prototype", convertBitmapToString(bmp)));                  try {                     HttpClient httpclient = new DefaultHttpClient();                     HttpPost httppost = new HttpPost(url);                     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));                     HttpResponse response = httpclient.execute(httppost);                     Cord responseStr = EntityUtils.toString(response.getEntity());                     Log.i(TAG, "doFileUpload Response : " + responseStr);                     handler.sendEmptyMessage(1);                 } catch (Exception eastward) {                     System.out.println("Mistake in http connexion " + e.toString());                     handler.sendEmptyMessage(0);                 }             }         });         t.beginning();      }      public String convertBitmapToString(Bitmap bmp){         ByteArrayOutputStream stream = new ByteArrayOutputStream();         bmp.compress(Bitmap.CompressFormat.PNG, 90, stream); //shrink to which format yous want.         byte[] byte_arr = stream.toByteArray();         String imageStr = Base64.encodeBytes(byte_arr);         return imageStr;     } }        

Make easy money with infolinks

Now the Activity that implements it.

Note : Make sure you select the prototype from the Gallery, because this demo is designed for selecting from Gallery.

MainActivity

package com.coderzheaven.uploadimage;  import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Packet; import android.os.Handler; import android.bone.Message; import android.provider.MediaStore; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView;  import java.io.IOException;  public class MainActivity extends AppCompatActivity implements View.OnClickListener {      public static final String TAG = "Upload Image";      // I am using my local server for uploading paradigm, you should replace information technology with your server address     public static final String UPLOAD_URL = "https://coderzheaven.com/sample_file_upload/upload_image.php";      public static final Cord UPLOAD_KEY = "upload_image";      private int PICK_IMAGE_REQUEST = 100;      individual Button btnSelect, btnUpload;     individual TextView txtStatus;      private ImageView imgView;      private Bitmap bitmap;      private Uri filePath;      private String selectedFilePath;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);         setSupportActionBar(toolbar);          imgView = (ImageView) findViewById(R.id.imgView);         btnSelect = (Button) findViewById(R.id.btnSelect);         btnUpload = (Button) findViewById(R.id.btnUpload);         txtStatus = (TextView) findViewById(R.id.txtStatus);          btnSelect.setOnClickListener(this);         btnUpload.setOnClickListener(this);      }      Handler handler = handler = new Handler() {         @Override         public void handleMessage(Message msg) {             Log.i(TAG, "Handler " + msg.what);             if (msg.what == 1) {                 txtStatus.setText("Upload Success");             } else {                 txtStatus.setText("Upload Fault");             }         }      };      private void showFileChooser() {         Intent intent = new Intent();         intent.setType("image/*");         intent.setAction(Intent.ACTION_GET_CONTENT);         startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);     }      @Override     protected void onActivityResult(int requestCode, int resultCode, Intent data) {         super.onActivityResult(requestCode, resultCode, information);          if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && information.getData() != null) {              filePath = information.getData();             selectedFilePath = getPath(filePath);             Log.i(TAG, " File path : " + selectedFilePath);             endeavor {                 bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);                 imgView.setImageBitmap(bitmap);             } catch (IOException e) {                 e.printStackTrace();             }         }     }      public Cord getPath(Uri uri) {         String[] projection = {MediaStore.Images.Media.Data};         Cursor cursor = managedQuery(uri, project, null, null, null);         int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.Information);         cursor.moveToFirst();         return cursor.getString(column_index);     }      private void uploadImage() {          UploadImageApacheHttp uploadTask = new UploadImageApacheHttp();         uploadTask.doFileUpload(UPLOAD_URL, bitmap, handler);      }      @Override     public void onClick(View 5) {         if (v == btnSelect)             showFileChooser();         else {             txtStatus.setText("Uploading Started...");             uploadImage();         }     } }        

Note : You should do networks operations inside a thread only.
AND you cannot modify UI elements inside a UIThread only.

< Upload Image

Add Base64.java to your project

Even so you can put in your own parcel but don't forget to change the parcel name otherwise you volition become error.

Server part

Create a folder named Upload_image_ANDROID in your htdocs folder and inside that create a file named upload_image.php and copy this lawmaking into information technology.

I am saying the htdocs folder because I am using XAMPP. You modify this co-ordinate to your use.

< ?php 	$base=$_REQUEST['prototype']; 	 $binary=base64_decode($base); 	header('Content-Type: bitmap; charset=utf-eight'); 	$file = fopen('uploaded_image.jpg', 'wb'); 	fwrite($file, $binary); 	fclose($file); 	echo 'Image upload complete!!, Please bank check your php file directory……'; ?>        

Now run your program and check the folder in which your php file resides.
Notation: Make sure your server is running.
Here I am uploading the icon image itself.

If you desire to upload some other file in your SDCARD y'all have to change this line to give the exact path

          Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);        

For example if I have to upload a file residing in my SDCARD I would modify the path like this.

          Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/android.jpg");        

Source Code

You can download the consummate Android studio Source Code from hither.

Delight send your comments to coderzheaven@gmail.com

doranyespire88.blogspot.com

Source: https://www.coderzheaven.com/2011/04/25/android-upload-an-image-to-a-server/

0 Response to "Uploading an Image to the Android Studio"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel