Hello everyone,

Check out the popular posts from Coderzheaven.com

Uploading and Downloading of files – Popular and Useful posts from CoderzHeaven

In one of the previous posts I have shown one method to upload an image in android.
Here is another method to upload a media file like images,audio or video in android.
Here is the main java file that does the upload.
Here I am trying to open audio from the gallery. However you can change it to image or video according to your need.
The code for upload will not change since we change only the code for opening the gallery. We use only the path of the selected file whether it is image or video or audio to upload.

Android File Upload

These are for downloading files from the server.

1. If you want to download file using VOLLEY, CHECK HERE.
2. How to Download an image in ANDROID programatically?
3. How to download a file to your android device from a remote server with a custom progressbar showing progress?


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

        android:text="Select File" />

        android:text="Upload File" />

        app:layout_constraintTop_toTopOf="parent" />



package file_upload_demo.coderzheaven.com.fileuploaddemo;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, Handler.Callback {

    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int SELECT_AUDIO = 2;
    private String selectedPath;
    private Handler handler;
    private TextView tvStatus;

    public void onCreate(Bundle savedInstanceState) {
        tvStatus = findViewById(R.id.tvStatus);
        handler = new Handler(this);

    public void openGallery() {
        Intent intent = new Intent();
        startActivityForResult(Intent.createChooser(intent, "Select Image "), SELECT_AUDIO);

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_AUDIO) {
                Uri selectedImageUri = data.getData();
                selectedImageUri = handleImageUri(selectedImageUri);
                selectedPath = getRealPathFromURI(selectedImageUri);
                tvStatus.setText("Selected Path :: " + selectedPath);
                Log.i(TAG, " Path :: " + selectedPath);

    public static Uri handleImageUri(Uri uri) {
        if (uri.getPath().contains("content")) {
            Pattern pattern = Pattern.compile("(content://media/.*\\d)");
            Matcher matcher = pattern.matcher(uri.getPath());
            if (matcher.find())
                return Uri.parse(matcher.group(1));
                throw new IllegalArgumentException("Cannot handle this URI");
        return uri;

    public String getRealPathFromURI(Uri uri) {
        String filePath = "";
        String wholeID = DocumentsContract.getDocumentId(uri);

        // Split at colon, use second item in the array
        String id = wholeID.split(":")[1];

        String[] column = {MediaStore.Images.Media.DATA};

        // where id is equal to
        String sel = MediaStore.Images.Media._ID + "=?";

        Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                column, sel, new String[]{id}, null);

        int columnIndex = cursor.getColumnIndex(column[0]);

        if (cursor.moveToFirst()) {
            filePath = cursor.getString(columnIndex);
        return filePath;

    public void onClick(View v) {
        if (v.getId() == R.id.selectFile) {
        if (v.getId() == R.id.uploadFile) {
            if (null != selectedPath && !selectedPath.isEmpty()) {
                tvStatus.setText("Uploading..." + selectedPath);
                FileUploadUtility.doFileUpload(selectedPath, handler);

    public boolean handleMessage(Message msg) {
        Log.i("File Upload", "Response :: " + msg.obj);
        String success = 1 == msg.arg1 ? "File Upload Success" : "File Upload Error";
        Log.i(TAG, success);
        return false;

Fie Upload Utility

package file_upload_demo.coderzheaven.com.fileuploaddemo;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class FileUploadUtility {

    static String SERVER_PATH = "http://your_domain/FileUploadTest/file_upload.php";

    public static void doFileUpload(final String selectedPath, final Handler handler) {

        new Thread(new Runnable() {
            public void run() {

                HttpURLConnection conn = null;
                DataOutputStream dos = null;
                DataInputStream inStream = null;
                String lineEnd = "rn";
                String twoHyphens = "--";
                String boundary = "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1 * 1024 * 1024;
                String responseFromServer = "";
                try {
                    //------------------ CLIENT REQUEST
                    FileInputStream fileInputStream = new FileInputStream(new File(selectedPath));
                    // open a URL connection to the Servlet
                    URL url = new URL(SERVER_PATH);
                    // Open a HTTP connection to the URL
                    conn = (HttpURLConnection) url.openConnection();
                    // Allow Inputs
                    // Allow Outputs
                    // Don't use a cached copy.
                    // Use a post method.
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                    dos = new DataOutputStream(conn.getOutputStream());
                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                            + selectedPath + "\"" + lineEnd);
                    // create a buffer of maximum size
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];
                    // read file and write it into form...
                    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);
                    // send multipart form data necesssary after file data...
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                    // close streams
                    Log.e("Debug", "File is written");

                } catch (MalformedURLException ex) {
                    Log.e("Debug", "error: " + ex.getMessage(), ex);
                    sendMessageBack(responseFromServer, 0, handler);
                } catch (IOException ioe) {
                    Log.e("Debug", "error: " + ioe.getMessage(), ioe);
                    sendMessageBack(responseFromServer, 0, handler);
                responseFromServer = processResponse(conn, responseFromServer);
                sendMessageBack(responseFromServer, 1, handler);


    private static String processResponse(HttpURLConnection conn, String responseFromServer) {
        DataInputStream inStream;
        try {
            inStream = new DataInputStream(conn.getInputStream());
            String str;

            while ((str = inStream.readLine()) != null) {
                responseFromServer = str;

        } catch (IOException ioex) {
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        return responseFromServer;

    static void sendMessageBack(String responseFromServer, int success, Handler handler) {
        Message message = new Message();
        message.obj = responseFromServer;
        message.arg1 = success;

Server Side

Now the server side , the code is written in Php.

// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploadedfile']['name']);
    echo "target_path: " .$target_path;

Things to keep in mind
1. Make sure your server is running.
2. Your server file path should be right.
3. Check your folder write permission in the server.

Please leave your valuable comments.

Source Code

You can download Android Studio source code from here.



  1. Pingback: How to Upload Multiple files in one request along with other string parameters in android? | Coderz Heaven

  2. Ali September 15, 2011 at 11:38 am

    Hi Thanks for this tutorial..
    Can you tell me how to store images in the emulator database and retrieve images from the database on to the emulator..
    example: doctor list with their images on the emulator..
    Waiting for your reply…

    • James September 22, 2011 at 10:27 pm

      Its not good to store images in the database. instead copy it into a folder in your Sdcard or application sandbox and save the path of that file in your database.
      For example if you have a number of images, copy it to drawable folder and store their names in the database and load it using that name. if you are downloading the images then download it to your application sandbox or sdcard and then load it from there.

  3. agatha September 26, 2011 at 1:13 am

    and how to view the uploaded files on Android in the form of a gallery? how do we take it from server to Android?

  4. Dattatraya November 14, 2011 at 1:02 pm

    Thanks for such nice tutorial. It is really help me.

  5. Marcos January 3, 2012 at 6:15 pm

    Thank you very much!!

  6. Simon April 16, 2012 at 1:03 pm

    Its good thanks but when i m trying to upload a file having size more than 100KB it fails, without showing any error after some time it jumps to another file for uploading. Can you suggest me for this …

    • Pavan Lingambudhi Seshadri Vasan July 28, 2015 at 5:26 am

      Hey…check your php.ini file and check your parameters such as ‘upload_max_filesize’, ‘post_max_size’, ‘max_input_time’, ‘max_execution_time’…once you set them up make sure you restart your apache service

  7. shehan June 8, 2012 at 8:05 am

    Hey I tried my best to compile this code. but it gives many more errors. So can you please send me a link to download a course code to this function as soon as possible.

    Thanks and Best Regards,

  8. Baskoro June 28, 2012 at 2:24 am

    Hi thanks for your tutorial,it’s awesome
    i try it in windows and it’s work
    but when i try in linux it’s doesn’t work
    what should i do??if trouble with folder permission i am not sure because i have modified the permission
    please help me..thank you 🙂

    • James June 28, 2012 at 3:55 pm

      @Baskoro :- Check what is the error message coming and paste it here.

  9. Malaiselvan August 14, 2012 at 5:18 am

    Hi, Thanks for this valuable post. It helps me a lot. I have 2 doubts before implementing this solution in my app.

    1. Will this program supports uploading files greater than 10MB
    2. My PHP webserver is hosted on a shared hosting server where the PHP upload limit is defined as 2 MB. In this case will this program upload files greater than 10MB?

    • James August 14, 2012 at 10:05 am

      1. Yes
      2. Yes, if Your server allows it.

      • Malaiselvan August 14, 2012 at 11:29 am

        I dont understand what do you mean by “if Your server allows it”. Do you mean the PHP.INI variable “post_max_size”

  10. Deepak August 29, 2012 at 6:19 am

    I checked out your code. I have a doubt.. Is this code allows user to send a very large file ie., greater than 20 MB.. Bcoz i tried many ways, i can upload 5MB of file sucessfully but wen i try to upload 20MB iam getting “OUT OF MEMORY” Exception.. Plz help

    • James August 29, 2012 at 7:45 pm

      Try increasing the buffersize.

  11. Sundar August 29, 2012 at 8:04 am

    Hi,thanks for the nice post.But i have a doubt in this.After the file was written to the server it takes more than to two minutes to get the response from the server.So i want to know that does the reading of response depends upon the device internet speed?

    • James August 29, 2012 at 7:41 pm

      Yes,of course.

      • Sundar September 7, 2012 at 10:41 am

        Iam using 3G connection to upload file to the server.Will exception rise does the 3G connection disabled while uploading the video?

  12. Pingback: Uploading and Downloading of files - Popular and Useful posts.

  13. venkat September 10, 2012 at 12:30 pm

    hi thanks for nice post.
    i want to send some more parameters with the video.
    how to add that parameters to this code.
    like name,about the video etc can send to the service how to add parameter to this code?

  14. Dhaval September 25, 2012 at 8:20 am

    I am gettng “There was an error uploading the file, please try again!” all the times. also i am not getting the name of my file from the server. Help me out.

    • James September 25, 2012 at 6:53 pm

      hey Dhaval, please check your internet connection, server path and the file name variables. Also add the internet permission in the Android Manifest file.

      • Dhaval September 28, 2012 at 12:45 pm

        I got it. The “\” were missing in the code above, the line:
        String lineEnd = “rn”;
        should be String line End = “\r\n”;

        Also the line “dos.writeBytes(“Content-Disposition…”
        had same issue. Placed “\”s and all set.

        Thanks for you reply

  15. Administrator@GeeksDoor October 8, 2012 at 3:48 pm

    Hey nice post . It worked form me please provide the code to send parameters with this file . Like if i want to send “key” with this file . Please reply ASAP

  16. mike February 5, 2013 at 7:27 am

    can you help me with this. the code is correct yet i can’t upload the file. it was force close. “the application has stopped unexpectedly.please try again later. what should be the solution for this?

  17. terli February 23, 2013 at 7:11 am

    i got error in php file i tried to generate service in server it shows as follows( i am new to php please help me….. thank you)

    Warning: fopen(uploaded_image.jpg) [function.fopen]: failed to open stream: Permission denied in /home/inspirei/public_html/bramara/upload/img.php on line 5

    Warning: fclose(): supplied argument is not a valid stream resource in /home/inspirei/public_html/bramara/upload/img.php on line 7
    Image upload complete!!, Please check your php file directory……

    • James February 23, 2013 at 2:49 pm

      Check your permissions in the PHP Server directory. You should set a write permission for the image to be uploaded in the server.

  18. mawmawlagi March 22, 2013 at 5:16 am

    thx for code..but i have error like this..
    Notice: Undefined index: uploads in C:\xampp\htdocs\upload_test\upload_media_test.php on line 5

    what’s wrong?? please help me..thx

  19. vikrant April 23, 2013 at 7:20 am

    dos.writeBytes(“Content-Disposition: form-data; name=”uploadedfile”;filename=”” + selectedPath + “”” + lineEnd);

    getting error on this lines plz help me out

    • James April 23, 2013 at 12:39 pm

      What is the error? can you please paste it here.

    • Rishabh August 21, 2013 at 5:29 am

      To resolve syntax error in Vikrant post

      dos.writeBytes(“Content-Disposition: form-data; name=\”uploaded_file\”;filename=\””+ selectedPath + “\”” + lineEnd);

  20. Rishabh August 21, 2013 at 5:24 am

    dos.writeBytes(“Content-Disposition: form-data; name=”uploadedfile”;filename=”” + selectedPath + “”” + lineEnd);

    getting error on this lines plz help me out

    Error : Syntax error on Tokens, delete this tokens

    • Geet October 28, 2013 at 7:01 am


      dos.writeBytes(“Content-Disposition: form-data; name=’uploaded_file’;filename='”
      + fileName + “‘” + lineEnd);

      • David March 1, 2014 at 5:19 pm

        I’ve used the next line to try and handle the code error –

        dos.writeBytes(“Content-Disposition: form-data; name=’uploaded_file’;filename='”+ fileName + “‘” + lineEnd);

        But now only – fileName – is being an error – anyone knows why is that?

        • James March 2, 2014 at 4:23 pm

          There is a “semicolon” in between your code in param “writeBytes”…
          remove that…

          • Gaurav bansal April 11, 2014 at 6:35 am

            Can you exactly give the line because still i am getting error.

  21. Victor October 9, 2013 at 1:33 pm

    Hi i need to upload audio file to a online server and download it.

    please help.

  22. android October 10, 2013 at 7:23 am

    09-28 03:46:14.554: E/Debug(10081): Server Response
    09-28 03:46:14.584: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 5
    09-28 03:46:14.594: E/Debug(10081): Server Response
    09-28 03:46:14.604: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 10
    09-28 03:46:14.604: E/Debug(10081): Server Response
    09-28 03:46:14.604: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 12
    09-28 03:46:14.604: E/Debug(10081): Server Response There was an error uploading the file, please try again!
    09-28 03:46:14.614: E/Debug(10081): Server Response Notice: Undefined index: uploadedfile in C:\xampp\htdocs\android\audio.php on line 17
    09-28 03:46:14.614: E/Debug(10081): Server Response filename: target_path: uploads/

    • Reejesh February 17, 2018 at 8:30 am

      same problem here

  23. Geet October 28, 2013 at 6:57 am

    Its Working. But how can i implement progress bar with calculating uploaded bytes with this Example?

  24. Mugdha Kaushik January 9, 2014 at 5:15 pm

    Add this line before loop otherwise zero kb data is uploaded on server.
    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    System.out.println(“Inside while loop”);
    outputStream.write(buffer, 0, bufferSize);
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);


    • James January 31, 2014 at 6:20 pm

      Thanks for the information.

  25. Sam March 10, 2014 at 1:52 pm

    Hi very nice post. But this code failed when uploading file size greater than 20MB i.e it throws exception OutOfMemory. How do I increase the buffer size? or any other way to resolve this.


  26. seema March 12, 2014 at 1:11 pm

    should we follow these ” How to create a new Virtual SD card in emulator in ANDROID? How to start emulator with the created SDCard?” and “How to add files like images inside your emulator in ANDROID?” tutorials to open the emulator? thanks

  27. Balint March 15, 2014 at 6:57 pm

    I always get 03-15 19:48:59.414: E/Debug(32243): Server Response There was an error uploading the file, please try again!filename: target_path: Upload/
    Why? When I am running your code, filename is known but it looks like it is not forwarded with the code

    • James March 22, 2014 at 4:46 pm

      Did you check the file path? it is correct?
      Did you check for null before uploading the file?

  28. Anand Kumar Jha March 29, 2014 at 2:15 pm

    Nice post. Thanks a lot for these genius posts.

  29. Ketul April 8, 2014 at 1:57 pm

    Hi I have tried your code for client and server both, and I am getting below response

    Server Response There was an error uploading the file, please try again!filename: target_path: upload/

    Please help me out ..how to solve this and what is the issue ?

    • James April 15, 2014 at 5:33 pm

      Did you check your server folder permission where you are uploading the file.

  30. Shinto Joseph April 25, 2014 at 4:25 pm

    this code not works on android kitkat any solution?

  31. Valkesh patel June 19, 2014 at 2:29 am

    Hy, I want to upload large file About 50MB, but I was got error of out of memory.
    I convert video file in to bytearray then is getting error.

    I upload video like this. record video and then convert in bytearry for encode base64 and getting string value from encoding file and post data in to our server.
    please have a solution of that issue then help me. Thank you in advance.

  32. yuki June 24, 2014 at 2:14 pm

    i got error, Error converting result java.io.IOException: Attempted read on closed stream.

    My LOG cant show before dos = new DataOutputStream(conn.getOutputStream());

  33. bhawna October 7, 2014 at 4:47 pm

    hllo sr where we place php code in android??
    tell me

    • James October 9, 2014 at 10:36 am

      In Your server…

  34. Nehal Ptael August 7, 2015 at 6:19 am

    I want to upload image, video and audio together. How can i do that with this code ?

  35. sanjay sharma April 2, 2017 at 7:13 am

    /* Add the original filename to our target path.
    Result is “uploads/filename.extension” */
    $target_path = $target_path . basename( $_FILES[‘uploadedfile’][‘name’]);

    i m not getting that what would be the uploadedfile name bcos user can select any file from gallery

    • James April 2, 2017 at 2:31 pm

      uploadedfile is the one selected by the user from the gallery.

  36. Jaydip June 21, 2017 at 12:00 pm

    how to Handle Breakdown while uploading and how to Resumable uploading like google play store in android.

    • James June 21, 2017 at 5:08 pm

      For resuming you server should support it.

  37. shailesh July 21, 2017 at 6:16 am

    No get any response from server

    • James July 24, 2017 at 1:34 am

      What error are you getting?

  38. shailesh July 21, 2017 at 8:43 am

    php codeignator not work pls help

  39. Kayode Banjo July 23, 2017 at 7:34 am

    Hello, Running this code, I am getting: HTTP Response: Bad Gateway 502.
    How can i resolve this issue?

    • James July 24, 2017 at 1:30 am

      Kayode, It would be better to check your server.

      “The server was acting as a gateway or proxy and received an invalid response from the upstream server.” There are many other 5xx server error messages, all of which boil down to: “The server failed to fulfill an apparently valid request.”

  40. shivpal singh August 3, 2017 at 10:13 am

    is it work of pdf and doc files also

    • James August 4, 2017 at 5:53 am

      It will work on any file, but depends on the server side code.

      • Sarim September 12, 2017 at 6:23 pm

        cannot resolve symbol uploadfile?

        • Sarim September 12, 2017 at 6:26 pm

          dos.writeBytes(“Content-Disposition: form-data; name=”uploadedfile”;filename=”” + selectedPath + “”” + lineEnd);

          cannot resolve symbol uploadfile?
          how resolve it?

          • Morteza November 6, 2017 at 1:31 pm

            use ( \ ) before ( each ” )

  41. rahul December 13, 2017 at 5:24 pm

    Thanks For tutorial, but now I Want to upload image with some parameters like name,Description to save mysql database from where i can pass these parameters??

  42. Rahul Kumar March 13, 2018 at 12:01 pm

    Thanks for the great tutorial


Leave a Reply

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




Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.