Image Upload with Multipart Request Using Android Volley

Http Multipart requests are used to send heavy data data or files like audio and video to the server. Android Volley gives you a very faster and optimized environment to send heavy data or files to the server. Here I post a image file selected from the gallery.
How to capture image from camera?

Creating Server Side Scripts

The first thing we need is to create our server side web services. For server side I am using PHP and MySQL. And for this I am using Wamp server. You can still use xampp or any other application. Now follow the steps to create your web service to handle the file upload.

  •  Go to your server’s root directory (c:/wamp/www) and create a new folder. I created AndroidUploadImage.
  • Inside the folder create a folder named uploads, in this folder we will save all the uploaded images.
  • Create a file named upload.php and write the following code.
    <?php
        // Path to move uploaded files
        $target_path = dirname(__FILE__).'/uploads/';
        if (isset($_FILES['image']['name'])) {
            $target_path = $target_path . basename($_FILES['image']['name']);
            try {
                // Throws exception incase file is not being moved
                if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
                    // make error flag true
                    echo json_encode(array('status'=>'fail', 'message'=>'could not move file'));
                }
                // File successfully uploaded
                echo json_encode(array('status'=>'success', 'message'=>'File Uploaded'));
            } catch (Exception $e) {
                // Exception occurred. Make error flag true
                echo json_encode(array('status'=>'fail', 'message'=>$e->getMessage()));
            }
        } else {
            // File parameter is missing
            echo json_encode(array('status'=>'fail', 'message'=>'Not received any file'));
        }
    ?>

Creating an Android Project

  1. Open Android Studio and create a new project (I created ImageUpload)
    How to create an android project ?
  2. Now add VolleyPlus to your project. You can quickly add it using gradle. Extract Gradle Scripts and open build.gradle (Module: app)
  3. Now inside dependencies block add the following line
    compile 'dev.dworks.libs:volleyplus:+'
  4. So your dependencies block will look like
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:24.0.0'
        compile 'dev.dworks.libs:volleyplus:+'
    }
  5. Now click on Sync Project With Gradle Icon from the top menu
  6. And it will automatically download and add volley library to your project.
  7. Now we need to create the following layout.
    Volley Image Upload Layout
  8. For creating the above layout you can use the following xml code
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp"
        tools:context="org.snowcorp.imageupload.MainActivity"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Upload Image using Volley"
            android:id="@+id/textView"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="10dp"/>
        <Button
            android:id="@+id/button_choose"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:text="Browse Image"
            android:textColor="#fff"
            android:layout_gravity="center_horizontal"
            android:layout_margin="20dp"
            android:padding="10dp"/>
        <ImageView
            android:id="@+id/imageView"
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:background="@drawable/border"
            android:layout_gravity="center_horizontal"
            android:padding="5dp"
            android:layout_margin="20dp"/>
        <Button
            android:id="@+id/button_upload"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:text="upload"
            android:textColor="#fff"
            android:layout_gravity="center_horizontal"
            android:layout_margin="20dp"/>
    </LinearLayout>
  9. Now lets come to MainActivity.java

    public class MainActivity extends AppCompatActivity {
        private ImageView imageView;
        private Button btnChoose, btnUpload;
        public static String BASE_URL = "http://192.168.1.100/AndroidUploadImage/upload.php";
        static final int PICK_IMAGE_REQUEST = 1;
        String filePath;
  10. Now implement OnClickListener interface to our buttons.
    btnChoose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            imageBrowse();
        }
    });
    btnUpload.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (filePath != null) {
                imageUpload(filePath);
            } else {
                Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
            }
        }
    });
  11. Now we will create a method to choose image from gallery. Create the following method.
    private void imageBrowse() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
    }
  12. To complete the image choosing process we need to override the following method.
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if(requestCode == PICK_IMAGE_REQUEST){
                Uri picUri = data.getData();
                filePath = getPath(picUri);
                imageView.setImageURI(picUri);
            }
        }
    }
    // Get Path of selected image
    private String getPath(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        CursorLoader loader = new CursorLoader(getApplicationContext(),    contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }

    More information about Android Images, read chapter Amazing Facts of Android ImageView.

  13. Now run your application and if you can choose image from gallery then you can move ahead. In below snapshot you can see mine app is working.Image Upload Using Volley
  14. Now we need to create one more method that will upload the image to our server. Create the following method in MainActivity class.
    private void imageUpload(final String imagePath) {
        SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.d("Response", response);
                        try {
                            JSONObject jObj = new JSONObject(response);
                            String message = jObj.getString("message");
                            Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                        } catch (JSONException e) {
                            // JSON error
                            e.printStackTrace();
                            Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
        smr.addFile("image", imagePath);
        MyApplication.getInstance().addToRequestQueue(smr);
    }
  15. So the final complete code for our MainActivity.java file would be like
    public class MainActivity extends AppCompatActivity {
        private ImageView imageView;
        private Button btnChoose, btnUpload;
        public static String BASE_URL = "http://192.168.1.100/AndroidUploadImage/upload.php";
        static final int PICK_IMAGE_REQUEST = 1;
        String filePath;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            imageView = (ImageView) findViewById(R.id.imageView);
            btnChoose = (Button) findViewById(R.id.button_choose);
            btnUpload = (Button) findViewById(R.id.button_upload);
            btnChoose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    imageBrowse();
                }
            });
            btnUpload.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (filePath != null) {
                        imageUpload(filePath);
                    } else {
                        Toast.makeText(getApplicationContext(), "Image not selected!", Toast.LENGTH_LONG).show();
                    }
                }
            });
        }
        private void imageBrowse() {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            // Start the Intent
            startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
        }
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (resultCode == RESULT_OK) {
                if(requestCode == PICK_IMAGE_REQUEST){
                    Uri picUri = data.getData();
                    Log.d("picUri", picUri.toString());
                    Log.d("filePath", filePath);
                    imageView.setImageURI(picUri);
                }
            }
        }
        private void imageUpload(final String imagePath) {
            SimpleMultiPartRequest smr = new SimpleMultiPartRequest(Request.Method.POST, BASE_URL,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            Log.d("Response", response);
                            try {
                                JSONObject jObj = new JSONObject(response);
                                String message = jObj.getString("message");
                                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
                            } catch (JSONException e) {
                                // JSON error
                                e.printStackTrace();
                                Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
            smr.addFile("image", imagePath);
            MyApplication.getInstance().addToRequestQueue(smr);
        }
        // Get Path of selected image
        private String getPath(Uri contentUri) {
            String[] proj = { MediaStore.Images.Media.DATA };
            CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null);
            Cursor cursor = loader.loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String result = cursor.getString(column_index);
            cursor.close();
            return result;
        }
    }
  16. Now at last add below permission to your application.
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  17. Finally run your app.
  18. You can also download my source code from below.

Full Source Code

About the author

Akshay Raj

View all posts

152 Comments

  • Thanq for the reply…
    and one more thing actually i follow your code and when i upload the image of more than 200KB, your app is crash i just want to upload the image of max. 500kB to my server…
    is there any way to compressed the any image size to the lower than 500KB

  • MyApplication.getInstance() can not resolve
    this error in mainactivity can give solution how to solve it

  • thanks sir your java code useful for me best
    one error when time browse image
    error is java.lang.nullpointerexception println need a message
    how to solve it

  • Hey, when I use your code library ‘dev.dworks.libs:volleyplus:+’ gives error because I am also using ‘com.mcxiaoke.volley:library-aar:1.0.0’ library for json parsing. Please give the solution for this.

      • 06-05 10:36:10.646 24011-24011/org.snowcorp.imageupload D/picUri: content://media/external/images/media/160682
        06-05 10:36:10.646 24011-24011/org.snowcorp.imageupload D/filePath: /storage/sdcard1/DCIM/Camera/IMG_20170426_185931346.jpg
        06-05 10:36:20.764 24011-24859/org.snowcorp.imageupload D/Volley: [4406] BasicNetwork.logSlowRequests: HTTP response for request= [lifetime=5325], [size=51], [rc=200], [retryCount=0]
        06-05 10:36:20.768 24011-24011/org.snowcorp.imageupload D/Response: {“status”:”fail”,”message”:”Not received any file”}

  • You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ” at line 1. this is the error am getting as response.along with the image am sending some strings.

  • hi I click on btnUpload and it shows me the following error:
    java.lang.NullPointerException: Attempt to invoke virtual method ‘void com.example.app.myapp.MyApplication.addToRequestQueue (com.android.volley.Request)’ on a null object reference

  • Hello akshay nice tutorial ,but i have four buttons and every button have separate upload file to server how can i do it ???

    • add your four file’s path to volley request
      smr.addFile("image1", imageOnePath);
      smr.addFile("image2", imageTwoPath);
      smr.addFile("image3", imageThreePath);
      smr.addFile("image4", imageFourPath);

  • HI Akshay Raj
    Iam facing a problem the file not sending to server its return false status and in api there is no file found in $_FILES[]

  • Hi nice post
    I have Two Questions:
    1. Can we upload any other string date with the image
    2. Can we upload multiple image ( i.e i have multiple images to upload)

    • yes, you can send string with smr.addStringParam("string1", "your string value"); and upload another image with smr.addFile("image2", imagePath2);

  • java.net.SocketTimeoutException: failed to connect to /192.168.1.100 (port 80) after 30000ms

  • When uploading a pdf do we have to make any changes to
    "String[] proj = { MediaStore.Images.Media.DATA };" line??

    • bro u have to remove ‘com.mcxiaoke.volley:library:1.0.18′
      from your dependence and sync again.
      dev.dworks.libs:volleyplus:+ has all the functionality of Volley:1.0.0 library so changed all other normal volley requests to Volleyplus because they re conflicting each other.

  • i cannot be able to sync, it fails to resolve compile ‘dev.dworks.libs:volleyplus:+’ kindly help.

      • This is the message i get.
        Error:(33, 13) Failed to resolve: dev.dworks.libs:volleyplus:+
        i am already using ‘com.mcxiaoke.volley:library:1.0.18’. In fact i also have synced without this too, but still could not resolve.

  • This is the message i get.
    Error:(33, 13) Failed to resolve: dev.dworks.libs:volleyplus:+
    i am already using ‘com.mcxiaoke.volley:library:1.0.18’. In fact i also have synced without this, still could not resolve.

  • Hi,
    Great post.
    Now what changes should i make in the php file and the android code to send some json string alongside the images such as imageId, datePosted etc

    • update your code:

      smr.addFile("image", imagePath);
      smr.addStringParam("imageId", "123");
      smr.addStringParam("datePosted", "31-10-2017");
        • <?php
          // Path to move uploaded files
          $target_path = dirname(__FILE__).'/uploads/';
          if (isset($_FILES['image']['name'])) {
              $target_path = $target_path . basename($_FILES['image']['name']);
              try {
                  // Throws exception incase file is not being moved
                  if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) {
                      // make error flag true
                      echo json_encode(array('status'=>'fail', 'message'=>'could not move file'));
                  }
                  // File successfully uploaded
                  echo json_encode(array('status'=>'success', 'message'=>'File Uploaded',
                                            'imageId'=>$_POST['imageId'], 'datePosted'=>$_POST['datePosted']));
              } catch (Exception $e) {
                  // Exception occurred. Make error flag true
                  echo json_encode(array('status'=>'fail', 'message'=>$e->getMessage()));
              }
          } else {
              // File parameter is missing
              echo json_encode(array('status'=>'fail', 'message'=>'Not received any file'));
          }
          ?>
          
          • Hi Ajay thanks a lot for your assistance on the previous comment
            I am facing a new issue earlier i was receiving parameters sent from android to php using $_POST[].Now i have migrated my pages to a godaddy domain (have updated link in android app) post migration i am not getting response from my android file to php using $_POST[].
            Kindly suggest

  • MyApplication.getInstance().addToRequestQueue(smr);
    what is MyApplication in this line ,please guide me, thanks

    • MyApplication.java is a Singleton Class. you can see full code of MyApplication.java here and you need to add your Singleton Class to Manifest.xml

      ....
          <application
              android:name=".MyApplication"
              ....
  • hello,
    im using volleyplus library to upload multipart image on server.
    but if image size 5mb then image content on server is empty and i dont want to compress my image.
    whats the problem

  • when i checked from advanced rest api client its fine ,
    but when i make a http call from android device its giving 406 BasicNetwork.performRequest: Unexpected response code 406.. Can you tell me why this happening .?

  • thank you for this example its really helpful,
    what if i want to upload the file but with different name ?

      • hi AKshay , app give me error !
        Attempt to invoke virtual method ‘void com.example.exmap.upload.MyApplication.addToRequestQueue(com.android.volley.Request)’ on a null object reference

        • add MyApplication to manifest.xml

          <application android:name=".MyApplication"
                       android:allowbackup="true"
                       android:icon="@drawable/ic_launcher"
                       android:label="@string/app_name"
                       android:theme="@style/AppTheme">
  • Its always saying “Not received any file” from php, ı used your source code too. Its getting image urls from device but when it sends it is giving this error. Thanks for your help.

  • Hello sir, thanks for the wonderful tutorial its helped alot. I would like you to help me and point out what changes i have to make to the php file so that i can upload multiple files (I have already changed the android part and each time i upload it says file uploaded but i only see one file on my server instead of the three files am sending) thanks in advance

  • Thank you for this
    But when i try to upload the picture it shows “Could not move”
    can you help me with this error please

      • Thank you for your fast response.
        But it didn’t work.By the way am working with local server Apache on OSX high sierra

  • Thank you for your fast answer bit it’s still not working.
    Am working with local server Apache on OSX High Sierra

  • I used your source code Its always saying “Not received any file” from php. I added runtime permission but still error remain same Thanks for your help.

  • facing this error by using vollyplus library..
    Error:Execution failed for task ‘:app:transformDexArchiveWithExternalLibsDexMergerForDebug’.
    > com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

    • add multiDexEnabled true in build.gradle and clear your project then rebuild.

      defaultConfig {
          applicationId "com.example.app"
          ...
          multiDexEnabled true
      }
      
      • sir after doing the above thing ..still it is showing same error
        Error:Execution failed for task ‘:app:transformDexArchiveWithExternalLibsDexMergerForDebug’.
        > java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

    • you are not sending the right parameters. check parameters in volley request and php file. sorry for late reply.

  • how to upload multiple image on server i try to do this
    for (int i=0;i<image_path.size();i++) {
    smr.addFile("image"+(i+1), image_path.get(i));
    }

  • Спасибо Akshay Raj! Но у меня проблема ‘could not move file’
    I change:
    public static String BASE_URL = “http://annabalab.000webhostapp.com/upload.php”;
    I check $_FILES[‘image’][‘error’].
    UPLOAD_ERR_PARTIAL
    VALUE: 3; The download file was only partially received.
    Создал папку uploads in public_html
    Help me please!

  • Hi, I am a newbie to this library, will anyone can tell me, I want to attach a filename and filedata( as bas64 string) inside the JSONRequest. How can I update this solution?
    Please kindly provide some solution…

  • Thanks for the excellent tutorial. When I add the “VolleyPlus:+” in my gradle, remaining Volley methods (OnError) which are using original volley library giving error. How can I resolve it?

  • Hello, I need your help, I am working on an application which creates a folder using application (activity) named “Scan” and then I want to upload images to that folder, kindly help me out. what changes can we do in PHP script or how to send a String Folder name with Image Upload. Thank You.

      • On the Server Side. I Want to pass the image to the Folder after its Created using Android app.

        • In upload.php file on server change path in this line –
          // Path to move uploaded files
          $target_path = dirname(__FILE__).’/uploads/’;
          for example if you want to save the image in “Scan” folder then replace “uploads” with “Scan” –
          // Path to move uploaded files
          $target_path = dirname(__FILE__).’/Scan/’;

          • That will upload the File to the Pre-Created Folder, named “Scan”. I want to create a folder using one Activity of android and pass this image to the folder created from that activity. For Better Understanding user creates a folder in htdocs/training/printer named HP10c after that, the location should be passed to next activity of Image Upload where the image is uploaded to this created folder or directory on the server.

          • You can pass location string from one activity to another using
            Intent intent= new Intent(this ,SecondActivity.class);
            intent.putExtra("folder_path","/folder/path/for/image/");
            startActivity(intent);

            And receive in second activity using following code –
            Intent intent = getIntent();
            String path = intent.getStringExtra("folder_path");

            Now you will have to send this path to server via an ajax call.
            Once you get the path on server, use this code to create folder using php –
            if (!file_exists('path/to/directory')) {
            mkdir('path/to/directory', 0777, true);
            }

            Once the folder is created, send your image file to server and save it to that folder. To remember the path of folder created before sending the image, store it in session variable.

          • Thanks for the Reply, Directory making is Already done using Http Post.
            Problem Lies that the File Upload.php as Stated in the tutorial should be inside the folder created “Scan” to upload images. As you can see upload.php is still on server main directory htdocs folder, not in lampp/htdocs/scan/hp10c as if it’s just created using previous activity.
            Now the upload.php has Target path which is static, dirname(__FILE__)./’upload’/;
            Even if I paste it into printer folder, it will upload the image to printer/uploads, but I want to upload it to /hp810c which is created by the user using Android Application, and Upload.php is outside this.
            I want to know how can we pass Dynamic Path to the PHP Script using Same activity.
            Like $Stringhow= “hp810c”
            target_path= dirname(__FILE__)./Stringhow/
            I am a beginner with android app development your detailed help will be appreciated.

  • Sir,i got error response while submitting to server “com.android.volley.error.VolleyError

  • Thank you Akshay for the amazing tutorial. But when I run the project, there is one error. The logcat shows:
    04-24 13:37:35.955 11336-11336/org.snowcorp.imageupload W/System.err: org.json.JSONException: Value string(68) of type java.lang.String cannot be converted to JSONObject
    04-24 13:37:35.955 11336-11336/org.snowcorp.imageupload W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
    04-24 13:37:35.955 11336-11336/org.snowcorp.imageupload W/System.err: at org.json.JSONObject.(JSONObject.java:159)
    04-24 13:37:35.955 11336-11336/org.snowcorp.imageupload W/System.err: at org.json.JSONObject.(JSONObject.java:172)
    04-24 13:37:35.955 11336-11336/org.snowcorp.imageupload W/System.err: at org.snowcorp.imageupload.MainActivity$4.onResponse(MainActivity.java:142)
    04-24 13:37:35.955 11336-11336/org.snowcorp.imageupload W/System.err: at org.snowcorp.imageupload.MainActivity$4.onResponse(MainActivity.java:136)
    04-24 13:37:35.955 11336-11336/org.snowcorp.imageupload W/System.err: at com.android.volley.request.SimpleMultiPartRequest.deliverResponse(SimpleMultiPartRequest.java:46)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at com.android.volley.request.SimpleMultiPartRequest.deliverResponse(SimpleMultiPartRequest.java:14)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at android.os.Handler.handleCallback(Handler.java:733)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at android.os.Looper.loop(Looper.java:136)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5314)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:680)
    04-24 13:37:35.960 11336-11336/org.snowcorp.imageupload W/System.err: at dalvik.system.NativeStart.main(Native Method)
    How can I deal with this problem?

  • Hello, Akshay thanks for the amazing tutorial. But when I ran that I encountered some errors. They are showed down below. Thank you again.
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: org.json.JSONException: Value string(68) of type java.lang.String cannot be converted to JSONObject
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at org.json.JSONObject.(JSONObject.java:160)
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at org.json.JSONObject.(JSONObject.java:173)
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at org.snowcorp.imageupload.MainActivity$3.onResponse(MainActivity.java:102)
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at org.snowcorp.imageupload.MainActivity$3.onResponse(MainActivity.java:97)
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at com.android.volley.request.SimpleMultiPartRequest.deliverResponse(SimpleMultiPartRequest.java:46)
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at com.android.volley.request.SimpleMultiPartRequest.deliverResponse(SimpleMultiPartRequest.java:14)
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:101)
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at android.os.Handler.handleCallback(Handler.java:739)
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
    04-24 14:37:06.311 11387-11387/org.snowcorp.imageupload W/System.err: at android.os.Looper.loop(Looper.java:145)
    04-24 14:37:06.321 11387-11387/org.snowcorp.imageupload W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6837)
    04-24 14:37:06.321 11387-11387/org.snowcorp.imageupload W/System.err: at java.lang.reflect.Method.invoke(Native Method)
    04-24 14:37:06.321 11387-11387/org.snowcorp.imageupload W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
    04-24 14:37:06.321 11387-11387/org.snowcorp.imageupload W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
    04-24 14:37:06.321 11387-11387/org.snowcorp.imageupload W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

    • ....
      public void onErrorResponse(VolleyError error) {
                      Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                  }
              }) {
              @Override
              public Map getHeaders() throws AuthFailureError {
                      Map  params = new HashMap();
                      params.put("User-Agent", "Nintendo Gameboy");
                      params.put("Accept-Language", "fr");
                      return params;
              }
      }
      ...
      • private void imageBrowse() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        //Intent galleryIntent = new Intent();
        galleryIntent.setType(“application/pdf”);
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        // Start the Intent
        startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
        }
        in your code i change like that, but i get error. what shoul i do?
        i want upload a pdf file

      • private void imageBrowse() {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        //Intent galleryIntent = new Intent();
        galleryIntent.setType(“application/pdf”);
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
        // Start the Intent
        startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
        }
        i change your code like that, but it not working for upload a pdf file. What should i do?

  • If your gradle is not being resolved,
    Uncheck the offline work setting in Gradle settings,
    No need to remove the previous Volley library, They work just fine with volley plus

  • Sir,I am very new learner in android studio.I just copied your above code but got compile error…and noticed red colored the following line which was in the last portion of the function imageUpload().
    MyApplication.getInstance().addToRequestQueue(smr);—–In this line,Myapplication was red i.e, it shows wrong in my pc.
    I want to know the reason.

  • I am getting this response, my file size is 5 mb
    Response: File did not upload: Could not move file

    it’s working fine if file size is lower than 1 mb

  • Hello sir, how could i upload an array of images?
    My code for adding the file.
    for (int i =0; i<filePath.size();i++) {
    smr.addFile("image["+i+"]", filePath.get(i));
    }

    In my server side code, i tried returning the image path to show it in my logs, but in only displays the name, not the full path.

  • Hello. I tried adding multiple images by inserting them in an ArrayList:

    for (int i =0; i<filePath.size();i++) {
    smr.addFile("image["+i+"]", filePath.get(i));
    }
    RequestHandler.getInstance(context).addToRequestQueue(smr);

    Now when I display each index in my logcat, it shows the full path.
    ex : /storage/emulated/0/Download/FB_IMG_1534074446574.jpg
    /storage/sdcard1/DCIM/PICTURE CITY/DSC_0454.JPG

    I tried foreach on php. Now tried to display the received array, the full path is shorten down to just the image name.

    $response['imagePath'] = $_FILES['image']['name'];

    this displays [{"imagePath":{"1":"DSC_0454.JPG","0":"FB_IMG_1534074446574.jpg"}} ]

    do you have any idea why? Thanks. BTW the code still works if i only upload one

  • Hi, i can compile the code, but it doesn’t upload any file in the uploads folder. i am using wamp though. After some time when i tried to upload images, there is a empty toast appears the below of the application.

  • Hi Hello,
    Nice Tutorial
    I am trying to insert the values in the database but i am not getting how to insert the values. I have read all your comments where you have not mentioned any database connectivity or neither u have used any insert query so how to insert data in mysql table.
    Thank you

  • I’m trying to upload an image and string .
    How can I upload them using only one SimpleMultiPartRequest?

  • Hi, I have tried your code but when i ran it on my mobile and click on browse image and select any pic then application close automatically.

  • Hy if i want to upload a document file like doc or txt file then which method is used

    • String[] mimeTypes =
      {“application/msword”,”application/vnd.openxmlformats-officedocument.wordprocessingml.document”, // .doc & .docx
      “application/vnd.ms-powerpoint”,”application/vnd.openxmlformats-officedocument.presentationml.presentation”, // .ppt & .pptx
      “application/vnd.ms-excel”,”application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”, // .xls & .xlsx
      “text/plain”,
      “application/pdf”,
      “application/zip”};
      …..
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
      intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : “*/*”);
      if (mimeTypes.length > 0) {
      intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
      }
      } else {
      String mimeTypesStr = “”;
      for (String mimeType : mimeTypes) {
      mimeTypesStr += mimeType + “|”;
      }
      intent.setType(mimeTypesStr.substring(0,mimeTypesStr.length() – 1));
      }

  • Como posso mandar ale da imagem o caminho do diretorio a ser armazenado no servidor, eu tente
    smr.addStringParam(“diretorio”, /imagens/ordemservico/”);
    pois tenho que enviar arquivos para diretorios diferentes mas no lado php nao consigo fazer