Their are several occasions when we need to upload a file from android device to server. Today we are gonna build an android app to upload an image and store it in the server. The server side will be powered by PHP.
1.Download and add android-async-http-library to your project.
2.Copy the below Code to your Activity Class:
*Don't forget to replace <YOUR WEB URL> with your web address.
3.Now Copy the below code to your activity's layout xml file:
4.create a folder in your server, namely 'images'.
5.Create a php file(imageupload.php) in the same directory(in server) and Copy the below code to it.
*imageupload.php
6. Add Internet and External Storage Permissions to your project manifest
That's all, Now run your project!
1.Download and add android-async-http-library to your project.
2.Copy the below Code to your Activity Class:
import java.io.ByteArrayOutputStream;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.bitmapImage;
import android.graphics.bitmapImageFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
@SuppressLint("NewApi")
public class MainActivity extends Activity {
ProgressDialog progressDialog;
String encodedString;
RequestParams params = new RequestParams();
String imagePath, fileName;
bitmapImage bitmapImage;
private static int LOAD_IMG_RESULT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
// Set Cancelable as False
progressDialog.setCancelable(false);
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent gallary = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(gallary, LOAD_IMG_RESULT);
}
// When Image is selected from Gallery
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == LOAD_IMG_RESULT && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.imageView);
// Set the Image in ImageView
imageView.setImagebitmapImage(bitmapImageFactory
.decodeFile(imagePath));
// Get the Image's file name
String splittedFileName[] = imagePath.split("/");
fileName = splittedFileName[splittedFileName.length - 1];
// Put file name in Async Http Post Param which will used in Php web app
params.put("fileName", fileName);
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
// When Upload button is clicked
public void startUploadImage(View v) {
// When Image is selected from Gallery
if (imagePath != null && !imagePath.isEmpty()) {
progressDialog.setMessage("Converting Image to Binary Data");
progressDialog.show();
// Convert image to String using Base64
encodeImagetoString();
// When Image is not selected from Gallery
} else {
Toast.makeText(
getApplicationContext(),
"You must select image from gallery before you try to upload",
Toast.LENGTH_LONG).show();
}
}
// AsyncTask - To convert Image to String
public void encodeImagetoString() {
new AsyncTask<Void, Void, String>() {
protected void onPreExecute() {
};
@Override
protected String doInBackground(Void... params) {
bitmapImageFactory.Options options = null;
options = new bitmapImageFactory.Options();
options.inSampleSize = 3;
bitmapImage = bitmapImageFactory.decodeFile(imagePath,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmapImage.compress(bitmapImage.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
return "";
}
@Override
protected void onPostExecute(String msg) {
progressDialog.setMessage("Calling Upload");
// Put converted Image string into Async Http Post param
params.put("image", encodedString);
// Trigger Image upload
triggerImageUpload();
}
}.execute(null, null, null);
}
public void triggerImageUpload() {
makingHTTPCall();
}
// Make Http call to upload Image to Php server
public void makingHTTPCall() {
progressDialog.setMessage("Invoking Php");
AsyncHttpClient client = new AsyncHttpClient();
// Don't forget to change the IP address to your LAN address. Port no as well.
client.post("http://<YOUR WEB URL>/upload_image.php",
params, new AsyncHttpResponseHandler() {
// When the response returned by REST has Http
// response code '200'
@Override
public void onSuccess(String response) {
// Hide Progress Dialog box
progressDialog.hide();
Toast.makeText(getApplicationContext(), response,
Toast.LENGTH_LONG).show();
}
// When the response returned by REST has Http
// response code other than '200' such as '404',
// '500' or '403' etc
@Override
public void onFailure(int statusCode, Throwable error,
String content) {
// Hide Progress Dialog Box
progressDialog.hide();
// When Http response code is '404'
if (statusCode == 404) {
Toast.makeText(getApplicationContext(),
"Requested resource not found",
Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if (statusCode == 500) {
Toast.makeText(getApplicationContext(),
"Something went wrong at server end",
Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else {
Toast.makeText(
getApplicationContext(),
"Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
+ statusCode, Toast.LENGTH_LONG)
.show();
}
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// Dismiss the progress bar when application is closed
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
*Don't forget to replace <YOUR WEB URL> with your web address.
3.Now Copy the below code to your activity's layout xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/imgView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ImageView>
<Button
android:id="@+id/buttonLoadPicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0"
android:onClick="loadImagefromGallery"
android:text="Load Image" >
</Button>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:onClick="startUploadImage"
android:text="Start Upload" />
</LinearLayout>
4.create a folder in your server, namely 'images'.
5.Create a php file(imageupload.php) in the same directory(in server) and Copy the below code to it.
*imageupload.php
<?php
// Get image string posted from Android App
$base=$_REQUEST['image'];
// Get file name posted from Android App
$filename = $_REQUEST['filename'];
// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');
// Images will be saved under 'www/img/images' folder
$file = fopen('images/'.$filename, 'wb');
// Create File
fwrite($file, $binary);
fclose($file);
echo 'Image upload complete, Please check your php file directory';
?>
6. Add Internet and External Storage Permissions to your project manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
That's all, Now run your project!
No comments:
Post a Comment