Android Image Upload To Server Using MultiPart Form


Uploading data from Android to server can be an important part of your application. One such application is when you are making a App based on Images and you require to send those user images to a server attached to your app. 

The following project demonstrates you how to upload the images from your Android app to your web server.


The following project invloves both the Android Studio files and PHP server file.


First lets look at the project overview:


First, add the permissions for Camera and External memory access in the AndroidManifest.xml files:

AndroidManifest.xml:

xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ourcoaching.simpleimageupload">

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET">uses-permission
>
<uses-permission android:name="android.permission.CAMERA">uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE">uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
intent-filter>
activity>
application>

manifest>


Next, create a simple layout contating an ImageView and 3 Buttons for Gallery,Camera and Upload actions

xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ourcoaching.simpleimageupload.MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CAMERA"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.881"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.708" />

<Button
android:id="@+id/button3"
android:layout_width="211dp"
android:layout_height="wrap_content"
android:text="UPLOAD"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.922" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GALLERY"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.239"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.708" />

<ImageView
android:id="@+id/imageView"
android:layout_width="243dp"
android:layout_height="239dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.504"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.113"
app:srcCompat="@mipmap/ic_launcher" />


android.support.constraint.ConstraintLayout
>


Lets code the JAVA file now. 

Declare certain variables in MainActivity.class, which will be used in the code

private final String DEBUG_TAG="UPLOAD  ";
private final String url_upload="http://192.168.0.8/kk/imageUpload/test_upload.php";
private Button CAMERA,UPLOAD;
private ImageView imageView;
private Bitmap bitmap;
private boolean hasCamera = false, hasPermission = false;
private boolean memoryPermission=false;

// any fixed number
private final int CAMERAPERMISSION = 432,MEMORYPERMISSION=324;

// assigning request variables
private final int Capture_Camera = 221;

// variable to store image file path
private String mCurrentPhotoPath;

private MyUploadClass myUploadClass;

private ProgressDialog progressDialog;


Instantiate the UI variables in onCreate

CAMERA = (Button) findViewById(R.id.button);
UPLOAD=(Button)findViewById(R.id.button3);
imageView = (ImageView) findViewById(R.id.imageView);


Next, inside the oncreate method itself, check for the permissions for External memory access and Camera. Even though we have declared the permissions for the same in Manifest file, Android system requires users to grant these permissions in RunTime only.

Paste the following piece of code in onCreate method

// checking whether device has a camera hardware or not
hasCamera = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);

// checking for camera permissin and then requesting it if no permission granted

if (hasCamera) {
/* checking build version
android documentation says if build>KITKAT, then camera permission should be asked in runtime
else camera permission is given by default
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
hasPermission = true;
} else {
RequestCameraSystemPermissions();
}

if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
memoryPermission = true;
} else {
RequestMemorySystemPermissions();
}
} else {
hasPermission = true;
}
}


Paste the following three following methods in MainActivity.class


private void RequestCameraSystemPermissions() {
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.CAMERA)) {

// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

} else {

// No explanation needed, we can request the permission.

ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.CAMERA},
CAMERAPERMISSION);

// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}

private void RequestMemorySystemPermissions() {
if (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

} else {

// No explanation needed, we can request the permission.

ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
MEMORYPERMISSION);

// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

switch (requestCode) {
case CAMERAPERMISSION:

if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted, yay! Do the
// contacts-related task you need to do.
hasPermission = true;
Toast.makeText(this, "Camera Permission Granted", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Camera Permission denied", Toast.LENGTH_LONG).show();
hasPermission = false;
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;

case MEMORYPERMISSION:

if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted, yay! Do the
// contacts-related task you need to do.
memoryPermission = true;
Toast.makeText(this, "Ext Memory Permission Granted", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Ext Memory Permission denied", Toast.LENGTH_LONG).show();
memoryPermission = false;
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}


Now that we have the permission to use both the features on Device, lets code the further Java Code:

Declare the OnClick listeners for the buttons

@Override
protected void onResume() {
super.onResume();

CAMERA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
CaptureCameraImage();
} catch (IOException e) {
e.printStackTrace();
}
}
});

UPLOAD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UploadImageNow();
}
});
}


CaptureCameraImage() method, first check for Camera Hardware and required permissions. If all ok, then create and Camera Capture Intent and call that Intent.

private void CaptureCameraImage() throws IOException {
if (hasCamera) {
if (hasPermission) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imaFil=createImageFile();
if (imaFil!=null) {
// setting an image custm name and path
Uri filepath=Uri.fromFile(imaFil);
intent.putExtra(MediaStore.EXTRA_OUTPUT, filepath);
startActivityForResult(intent, Capture_Camera);

}else Toast.makeText(this,"There was a problem",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "requesting permission", Toast.LENGTH_SHORT).show();
RequestCameraSystemPermissions();
}
} else {
Toast.makeText(this, "no camera present", Toast.LENGTH_SHORT).show();
}
}

@SuppressLint("LongLogTag")
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "Ourcoaching.com_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Capture_Camera) {
GetImageFromActivityResult();
} else Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();


if (bitmap == null) {
Toast.makeText(this, "bitmap = null", Toast.LENGTH_SHORT).show();
} else {
imageView.setImageBitmap(bitmap);
}
}

private void GetImageFromActivityResult() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();

// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;

// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;

bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
imageView.setImageBitmap(bitmap);
}



UploadImageNow() method, check whether image is selected or not, if yes, then call the Async Class MyUploadClass to intitiate the Upload.

 private class MyUploadClass extends AsyncTask{

public String op="";
String fileName;

File sourceFile ;
String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";


@Override
protected void onPreExecute() {
super.onPreExecute();

if (!checknetworkstatus()){
cancel(true);
}else {
progressDialog=new ProgressDialog(MainActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Uploading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
}

@Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection httpURLConnection;

try {
Log.d(DEBUG_TAG+"input uri=",strings[1]);
Log.d(DEBUG_TAG+"input url=",strings[0]);
sourceFile= new File(strings[1]);
Log.d(DEBUG_TAG+"sourcefile=",sourceFile.toString());
fileName=sourceFile.getName();
Log.d(DEBUG_TAG+"filename=",fileName);

url=new URL(strings[0]);
httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);

httpURLConnection.setRequestMethod("POST");

String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
httpURLConnection.setDoOutput(true);

String metadataPart = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
+ "" + "\r\n";
String fileHeader1 = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"fileToUpload\"; filename=\""
+ fileName + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n";

long fileLength = sourceFile.length() + tail.length();

String fileHeader2 = "Content-length: " + fileLength + "\r\n";

String fileHeader = fileHeader1 + fileHeader2 + "\r\n";

String stringData = metadataPart + fileHeader;
Log.d(DEBUG_TAG+"stringData=",stringData);

long requestLength = stringData.length() + fileLength;

httpURLConnection.setRequestProperty("Content-length", "" + requestLength);
httpURLConnection.setFixedLengthStreamingMode((int) requestLength);
httpURLConnection.connect();

DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
out.writeBytes(stringData);
out.flush();

int progress = 0;
int bytesRead = 0;
byte buf[] = new byte[1024];
BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(sourceFile));

while ((bytesRead = bufInput.read(buf)) != -1) {
// write output
out.write(buf, 0, bytesRead);
out.flush();
progress += bytesRead; // Here progress is total uploaded bytes

//publishProgress(""+(int)((progress*100)/totalSize)); // sending progress percent to publishProgress
}

// Write closing boundary and close stream
out.writeBytes(tail);
out.flush();
out.close();
Log.d(DEBUG_TAG+"DOS CLOSE","ok");

// Get server response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line = "";
StringBuilder builder = new StringBuilder();
while((line = reader.readLine()) != null) {
builder.append(line);
}

Log.d(DEBUG_TAG+"output: ",builder.toString());
op=builder.toString();
reader.close();
return op;

} catch (MalformedURLException e) {
e.printStackTrace();
Log.d(DEBUG_TAG+"ERROR",e.toString());
} catch (IOException e) {
Log.d(DEBUG_TAG+"ERROR",e.toString());
e.printStackTrace();
}

return op;
}


@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.cancel();
Toast.makeText(MainActivity.this,"Process Finished: "+s,Toast.LENGTH_SHORT).show();
}


@Override
protected void onCancelled() {
super.onCancelled();
progressDialog.cancel();
Toast.makeText(MainActivity.this,"Cancelled",Toast.LENGTH_SHORT).show();
}

private NetworkInfo getActiveNetworkInfo() {
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(MainActivity.this.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo;
}

private boolean checknetworkstatus() {

boolean ch1 = false;
NetworkInfo networkInfo = getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isConnected() ||
(networkInfo.getType() != ConnectivityManager.TYPE_WIFI
&& networkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) {
// If no connectivity, cancel task and update Callback with null data.
ch1 = false;
} else ch1 = true;

return ch1;
}

}


Complete Java Code:

package com.ourcoaching.simpleimageupload;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {

private final String DEBUG_TAG="UPLOAD ";
private final String url_upload="http://192.168.0.8/kk/imageUpload/test_upload.php";
private Button CAMERA,UPLOAD;
private ImageView imageView;
private Bitmap bitmap;
private boolean hasCamera = false, hasPermission = false;
private boolean memoryPermission=false;

// any fixed number
private final int CAMERAPERMISSION = 432,MEMORYPERMISSION=324;

// assigning request variables
private final int Capture_Camera = 221;

// variable to store image file path
private String mCurrentPhotoPath;

private MyUploadClass myUploadClass;

private ProgressDialog progressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CAMERA = (Button) findViewById(R.id.button);
UPLOAD=(Button)findViewById(R.id.button3);
imageView = (ImageView) findViewById(R.id.imageView);

// checking whether device has a camera hardware or not
hasCamera = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);

// checking for camera permissin and then requesting it if no permission granted

if (hasCamera) {
/* checking build version
android documentation says if build>KITKAT, then camera permission should be asked in runtime
else camera permission is given by default
*/
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
hasPermission = true;
} else {
RequestCameraSystemPermissions();
}

if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
memoryPermission = true;
} else {
RequestMemorySystemPermissions();
}
} else {
hasPermission = true;
}
}
}


@Override
protected void onResume() {
super.onResume();

CAMERA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
CaptureCameraImage();
} catch (IOException e) {
e.printStackTrace();
}
}
});

UPLOAD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
UploadImageNow();
}
});
}

private void UploadImageNow() {
if (mCurrentPhotoPath!=null && bitmap!=null){
myUploadClass=new MyUploadClass();
myUploadClass.execute(url_upload,mCurrentPhotoPath);
}else Toast.makeText(this,"Please select an image",Toast.LENGTH_SHORT).show();

}

private void CaptureCameraImage() throws IOException {
if (hasCamera) {
if (hasPermission) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imaFil=createImageFile();
if (imaFil!=null) {
// setting an image custm name and path
Uri filepath=Uri.fromFile(imaFil);
intent.putExtra(MediaStore.EXTRA_OUTPUT, filepath);
startActivityForResult(intent, Capture_Camera);

}else Toast.makeText(this,"There was a problem",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "requesting permission", Toast.LENGTH_SHORT).show();
RequestCameraSystemPermissions();
}
} else {
Toast.makeText(this, "no camera present", Toast.LENGTH_SHORT).show();
}
}



@SuppressLint("LongLogTag")
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "Ourcoaching.com_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Capture_Camera) {
GetImageFromActivityResult();
} else Toast.makeText(this, "Cancelled", Toast.LENGTH_SHORT).show();


if (bitmap == null) {
Toast.makeText(this, "bitmap = null", Toast.LENGTH_SHORT).show();
} else {
imageView.setImageBitmap(bitmap);
}
}

private void RequestCameraSystemPermissions() {
if (ContextCompat.checkSelfPermission(getApplicationContext(),
android.Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.CAMERA)) {

// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

} else {

// No explanation needed, we can request the permission.

ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.CAMERA},
CAMERAPERMISSION);

// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}

private void RequestMemorySystemPermissions() {
if (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.

} else {

// No explanation needed, we can request the permission.

ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE},
MEMORYPERMISSION);

// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

switch (requestCode) {
case CAMERAPERMISSION:

if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted, yay! Do the
// contacts-related task you need to do.
hasPermission = true;
Toast.makeText(this, "Camera Permission Granted", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Camera Permission denied", Toast.LENGTH_LONG).show();
hasPermission = false;
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;

case MEMORYPERMISSION:

if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

// permission was granted, yay! Do the
// contacts-related task you need to do.
memoryPermission = true;
Toast.makeText(this, "Ext Memory Permission Granted", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "Ext Memory Permission denied", Toast.LENGTH_LONG).show();
memoryPermission = false;
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}


private void GetImageFromActivityResult() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();

// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;

// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;

bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
imageView.setImageBitmap(bitmap);
}



private class MyUploadClass extends AsyncTask{

public String op="";
String fileName;

File sourceFile ;
String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";


@Override
protected void onPreExecute() {
super.onPreExecute();

if (!checknetworkstatus()){
cancel(true);
}else {
progressDialog=new ProgressDialog(MainActivity.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Uploading...");
progressDialog.setCancelable(false);
progressDialog.show();
}
}

@Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection httpURLConnection;

try {
Log.d(DEBUG_TAG+"input uri=",strings[1]);
Log.d(DEBUG_TAG+"input url=",strings[0]);
sourceFile= new File(strings[1]);
Log.d(DEBUG_TAG+"sourcefile=",sourceFile.toString());
fileName=sourceFile.getName();
Log.d(DEBUG_TAG+"filename=",fileName);

url=new URL(strings[0]);
httpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);

httpURLConnection.setRequestMethod("POST");

String boundary = "---------------------------boundary";
String tail = "\r\n--" + boundary + "--\r\n";
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
httpURLConnection.setDoOutput(true);

String metadataPart = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"metadata\"\r\n\r\n"
+ "" + "\r\n";
String fileHeader1 = "--" + boundary + "\r\n"
+ "Content-Disposition: form-data; name=\"fileToUpload\"; filename=\""
+ fileName + "\"\r\n"
+ "Content-Type: application/octet-stream\r\n"
+ "Content-Transfer-Encoding: binary\r\n";

long fileLength = sourceFile.length() + tail.length();

String fileHeader2 = "Content-length: " + fileLength + "\r\n";

String fileHeader = fileHeader1 + fileHeader2 + "\r\n";

String stringData = metadataPart + fileHeader;
Log.d(DEBUG_TAG+"stringData=",stringData);

long requestLength = stringData.length() + fileLength;

httpURLConnection.setRequestProperty("Content-length", "" + requestLength);
httpURLConnection.setFixedLengthStreamingMode((int) requestLength);
httpURLConnection.connect();

DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
out.writeBytes(stringData);
out.flush();

int progress = 0;
int bytesRead = 0;
byte buf[] = new byte[1024];
BufferedInputStream bufInput = new BufferedInputStream(new FileInputStream(sourceFile));

while ((bytesRead = bufInput.read(buf)) != -1) {
// write output
out.write(buf, 0, bytesRead);
out.flush();
progress += bytesRead; // Here progress is total uploaded bytes

//publishProgress(""+(int)((progress*100)/totalSize)); // sending progress percent to publishProgress
}

// Write closing boundary and close stream
out.writeBytes(tail);
out.flush();
out.close();
Log.d(DEBUG_TAG+"DOS CLOSE","ok");

// Get server response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line = "";
StringBuilder builder = new StringBuilder();
while((line = reader.readLine()) != null) {
builder.append(line);
}

Log.d(DEBUG_TAG+"output: ",builder.toString());
op=builder.toString();
reader.close();
return op;

} catch (MalformedURLException e) {
e.printStackTrace();
Log.d(DEBUG_TAG+"ERROR",e.toString());
} catch (IOException e) {
Log.d(DEBUG_TAG+"ERROR",e.toString());
e.printStackTrace();
}

return op;
}


@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.cancel();
Toast.makeText(MainActivity.this,"Process Finished: "+s,Toast.LENGTH_SHORT).show();
}


@Override
protected void onCancelled() {
super.onCancelled();
progressDialog.cancel();
Toast.makeText(MainActivity.this,"Cancelled",Toast.LENGTH_SHORT).show();
}

private NetworkInfo getActiveNetworkInfo() {
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(MainActivity.this.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo;
}

private boolean checknetworkstatus() {

boolean ch1 = false;
NetworkInfo networkInfo = getActiveNetworkInfo();
if (networkInfo == null || !networkInfo.isConnected() ||
(networkInfo.getType() != ConnectivityManager.TYPE_WIFI
&& networkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) {
// If no connectivity, cancel task and update Callback with null data.
ch1 = false;
} else ch1 = true;

return ch1;
}

}
}


PHP file (to be placed in server or localhost, URL of file to be pasted in value url_upload, eg in my case 

 url_upload="http://192.168.0.8/kk/imageUpload/test_upload.php";




Download the code from GitHub



Related Tutorials