How to upload a file to server in android

In this tutorial we will learn how to upload a file to server in android and php. For uploading a file in android the file should be saved in your sd card and we requires the path of the image.  Suppose if we are selecting an image from gallery we need to get the path of that particular image selected. In my previous article How to set image in Imagview from Camera or Gallery i am explaining how to get image from gallery. Here we will first get the image from gallery using the same mechanism and upload to server.

Recomended to use android Volley library for doing this task which is most flexible way of file upload in android.

Steps

  1. Create new project in android studio
  2. Add the button to your layout file .
  3. Implement the code for uploading file in your activity’s java file

Create New project in android studio

Refer Android beginners app development guide if you are beginner or if you don’t know how to create project in android studio.

Add the button to your layout file

This step is specific to this tutorial. Your requirement may be upload the file on some other action, so you can do coding based on that. So here to create an upload button in your layout file using the below code.

<Button
android:id="@+id/btn_upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload" />

Implement the code for uploading file in your activity’s java file

Now simply add the following code to your activity. This will contain reference of the above button and while clicking on button it will open Gallery , and after selecting the image, it will come back to onActivityResult method of activity and start code for uploading file to server.

Here is the full code

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.provider.MediaStore;
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.Toast;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

private String upload_path;
ProgressDialog pDialog;

int serverResponseCode = 0;
private FileInputStream fileInputStream;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

pDialog = new ProgressDialog(this);

Button btn_upload = (Button) findViewById(R.id.btn_upload);
btn_upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 0);
}
});

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode == RESULT_OK) {

Uri selectedImageUri = data.getData();
upload_path = GetGalleryPath(selectedImageUri, this);
Upload();
}
}

public static String GetGalleryPath(Uri uri, Activity activity) {
String[] projection = { MediaStore.Images.Media.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = activity.managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}


private void Upload() {

try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new UploadFile().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "your api link");
} else {
new UploadFile().execute("your api link");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


private class UploadFile extends AsyncTask<String, Void, Void> {

String fileName = upload_path;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(upload_path);
private String Content;
private String Error = null;

protected void onPreExecute() {

pDialog.show();
}

protected Void doInBackground(String... urls) {
BufferedReader reader = null;
if (!sourceFile.isFile()) {

pDialog.dismiss();

Log.e("uploadFile", "Source File not exist");


} else {
try {
fileInputStream = new FileInputStream(sourceFile);

URL url = new URL(urls[0]);

conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);

dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available();

bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

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);

}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
serverResponseCode = conn.getResponseCode();
Content = conn.getResponseMessage();


} catch (Exception ex) {
Error = ex.getMessage();
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
}
return null;
}

protected void onPostExecute(Void unused) {
pDialog.dismiss();

try {

if (Content != null) {

Toast.makeText(getApplicationContext(),Content,Toast.LENGTH_SHORT).show();
if(Content.equalsIgnoreCase("OK")){

Toast.makeText(getApplicationContext(),"Your file uploaded successfully",Toast.LENGTH_SHORT).show();

}

}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

}

3.Now add the following php code to your api to save the file in your specified folder

<?php
 //path of the folder which file is to be saved
 $file_path = $_SERVER['DOCUMENT_ROOT'] ."/images"/";
 
 $file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
 if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
 echo "success";
 } else{
 echo "fail";
 }
 ?>

In my next tutorial i am explaining How to upload image as base64 encoded string in android which is more smartest way to upload image to server in android.

Similarly the tutorial How to download a file from server in android will show how to download a file or image from server and save to your sdcard

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

32 Comments

  1. amol February 11, 2019 Reply
  2. amol February 11, 2019 Reply
  3. 슈퍼카지노 June 20, 2018 Reply

Add a Comment

Your email address will not be published. Required fields are marked *