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
- Open Android Studio and create a new project (I created ImageUpload)
How to create an android project ? - Now add VolleyPlus to your project. You can quickly add it using gradle. Extract Gradle Scripts and open build.gradle (Module: app)
- Now inside dependencies block add the following line
compile 'dev.dworks.libs:volleyplus:+'
- 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:+' }
- Now click on Sync Project With Gradle Icon from the top menu
- And it will automatically download and add volley library to your project.
- Now we need to create the following layout.
- 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>
- 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;
- 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(); } } });
- 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); }
- 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.
- 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.
- 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); }
- 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; } }
- 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" />
- Finally run your app.
- You can also download my source code from below.
Hi let me know is compile ‘dev.dworks.libs:volleyplus:+’ open source.As i am making product i want only open source libs…
Yes this is open source library.
i just want to implement the validation on image during image selection means(Max size of 500KB) then how can i do it?
getting file size:-
File file = new File("/sdcard/Your_file");
long length = file.length() / 1024; // Size in KB
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
Getting file size
String fileSize = Long.toString(cursor.getLong(sizeIndex));
This method get file size in bytes
MyApplication.getInstance() can not resolve
this error in mainactivity can give solution how to solve it
use this file
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
use my source code Android-Image-Upload
can you please share SimpleMultiPartRequest.class?
use this library
compile 'dev.dworks.libs:volleyplus:+'
dependencies {
implementation ‘dev.dworks.libs:volleyplus:+’
}
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.
use this
dev.dworks.libs:volleyplus:+
library because this library has all request of Volley.i cannot sync, it fails to resolve. kindly help. thanks
Image upload using this library is not working
What is the problem? send me screenshot or log.
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”}
check internet permission in manifest.xml file. if you’re getting any problem again then contact me on Facebook. So that I can help you better.
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.
smr.addFile() function not send file to the server
Use runtime permission. I’m updating this post.
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
add MyApplication class to manifest file
android:name=".MyApplication"
...
Can this code work for video uploading ?
yes, you can upload videos.
how to upload pdf file
choose pdf file and add file path to volley request
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);
Are you sure
In case we want to send several to the server by inserting a link of each in the MySQL database, what should be done on the PHP and Android script? Thank you
I got null file path…what should i do?
add runtime permission in your activity.
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 withsmr.addFile("image2", imagePath2);
i want to send
smr.addFile("profile_url", IMAGE_PATH);
smr.addStringParam("access_token", YOUR_ACCESS_TOKEN);
smr.addStringParam("user_name", USER_NAME);
smr.addStringParam("user_email", USER_EMAIL);
smr.addStringParam("is_thumbnail", "1");
am trying to send multiple images in array format to server having different parameter how i can send multiple image
check this Upload Multiple Images Using Retrofit Library
How can I adapt this to send video?
first change intent for select video then add video path to
smr.addFile("video", VIDEO_PATH);
java.net.SocketTimeoutException: failed to connect to /192.168.1.100 (port 80) after 30000ms
check your ip address and then test your app
When uploading a pdf do we have to make any changes to
"String[] proj = { MediaStore.Images.Media.DATA };"
line??i cannot sync, it fails to resolve. kindly help. thanks
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.
post your logcat
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.
Can you send a screenshot of build.gradle file? (You can send me at Facebook)
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:
what should i update in php file, i can’t see any string although no failure message. thansk
how do i move the value added addStringParam to a variable within php
use
$_POST["image_name"]
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
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
Change “upload_max_filesize” to 800M in php.ini
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 .?
can you contact me via facebook so i can help you.
thank you for this example its really helpful,
what if i want to upload the file but with different name ?
use this method https://stackoverflow.com/questions/18705639/how-to-rename-uploaded-file-before-saving-it-into-a-directory
Thank you but I want to rename it before i send it because i am using loopback storage and using other api to save the image name with other information so i need to rename it before i send it with volley and then send that name in other volley post method
hi Akshay Raj, nice work , How request many file at the same time
add more files like this
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
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.
add runtime permission Android Runtime Permissions Request
I already did that in a other activitiy so like i said i used your source code too(Make the changes in PHP and phps url)
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
can you show me your android code for multiple files?
I tried uploading the code here but was unable so i created a git repo and uploaded it there along with the php (The problem is that i can only see one file in my uploads folder on the server) https://github.com/joshNic/And_Upload
I want to upload image with text how will i do it please tell me
smr.addStringParam(“name”, “abc def”);
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
Create uploads folder and change permission to read and write
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
Ok.. send me a screenshot of uploads folder info and send php.ini to my facebook so i can help you. My Facebook
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.
change folder permission
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.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
E/Volley: [80199] BasicNetwork.performRequest: Unexpected response code 400 for
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));
}
how to upload multiple image form loop like this
for (int i=0;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!
Thanks Akshay Raj! But i have problem ‘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.
I create folder uploads in public_html
Help me please!
i uploaded a image successfully. add runtime permission if you are using android 6 or newer. sorry for late reply.
what kind of runtime permission?
Check this Android Runtime Permissions Request
MyApplication.getInstance().addToRequestQueue(smr);
What is my application in the end?
MyApplication is Singleton Pattern file. check for more information about Singleton Pattern
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…
This tutorial is for multipart images
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?
can you send me screenshots?
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.
where do you want to create folder? Phone or Server?
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.
$folder = $_POST[“folder_name”];
$target_path= dirname(__FILE__)./$folder/
Sir,i got error response while submitting to server “com.android.volley.error.VolleyError
show me full error
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)
this is server side error
Thanks, very appreciate that!
how to add header to smr
Thank u so much
For pdf file upload what changes i need to do?? in your code
sorry for late reply.
check this
intent.setType("application/pdf");
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?
check this https://stackoverflow.com/questions/28978581/how-to-make-intent-settype-for-pdf-xlsx-and-txt-file-android
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.
you can find MyApplication.java in source codes
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
change file size in php.ini
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
check this https://www.androidlearning.com/android-upload-multiple-images/. sorry for late reply
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
you can upload files through this tutorial. if you want to insert any data to database you need to create database and create sql connection. you can learn database connection from this tutorial.
Android Login Registration System with PHP, MySQL and Sqlite
Thank you so much it worked ?
Keep it up.
I’m trying to upload an image and string .
How can I upload them using only one SimpleMultiPartRequest?
Sorry for late reply.
smr.addFile("image", imagePath);
smr.addStringParam("imageId", "123");
http://btpcbhopal.com/mobileapp/upload.php
sir this url not work with this SimpleMultiPartRequest method
Volley: [8918] BasicNetwork.performRequest: Unexpected response code 403 for
but for this url its work
http://bhssolution.com/demo/upload.php
change permission of uploads folder to 775 and also check your php.ini file for file_uploads and upload_max_filesize.
please send me the logic for sending multiple image
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.
add runtime permission to your app
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
Desculpe pela resposta tardia. Você precisa criar uma pasta por php para armazenar imagens em um diretório diferente.