Hello friends, In this post, I will show you how to upload Image/Video/Any Files to the Server in Android using Retrofit 2. In Retrofit 2 Image or any type of files will be uploaded as Multipart. The File is received using php.
This Code is Updated with Multiple File Upload.
Don't forget to add the following permission in your manifest file
Open your app level build.gradle file add the following lines.
Create AppConfig.java and replace it with the following lines
Create ApiConfig.java and replace it with the following lines
Create ServerResponse.java and replace it with the following lines. The Data Names are same as the Names in PHP(for example success and message)
Create activity_main.xml and Paste the following lines
To Upload Multiple files, I made some changes as in the following.
Create a PHP file named as upload_multiple_files.php and paste the following lines.
Add the following interface for uploading multiple files in ApiConfig.java
This Code is Updated with Multiple File Upload.
Download From Github
Post your doubts and comments in the comments section.
Upload Single File
Web Part:
Create a PHP file named as upload_image.php and paste the following lines.<?php
$target_dir = "uploads/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();
// Check if image file is a actual image or fake image
if (isset($_FILES["file"]))
{
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name))
{
$success = true;
$message = "Successfully Uploaded";
}
else
{
$success = false;
$message = "Error while uploading";
}
}
else
{
$success = false;
$message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
?>
Project Structure
Create a new Project in Android Studio with the required Specifications.Codes:
AndroidManifest.xmlDon't forget to add the following permission in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
build.gradleOpen your app level build.gradle file add the following lines.
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.3.0'
// dependency for Retrofit 2
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
}
AppConfig.javaCreate AppConfig.java and replace it with the following lines
class AppConfig {
private static String BASE_URL = "http://mushtaq.16mb.com/";
static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}
ApiConfig.javaCreate ApiConfig.java and replace it with the following lines
interface ApiConfig {
@Multipart
@POST("retrofit_example/upload_image.php")
Call uploadFile(@Part MultipartBody.Part file, @Part("file") RequestBody name);
}
ServerResponse.javaCreate ServerResponse.java and replace it with the following lines. The Data Names are same as the Names in PHP(for example success and message)
class ServerResponse {
// variable name should be same as in the json response from php
@SerializedName("success")
boolean success;
@SerializedName("message")
String message;
String getMessage() {
return message;
}
boolean getSuccess() {
return success;
}
}
activity_main.xmlCreate activity_main.xml and Paste the following lines
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:scrollbars="none"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:id="@+id/preview"
android:layout_width="match_parent"
android:layout_height="300dp"
android:scaleType="centerCrop"
android:src="@drawable/placeholder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<Button
android:id="@+id/pick_img"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Pick Image" />
<Button
android:id="@+id/pick_vdo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:text="Pick Video" />
</LinearLayout>
<Button
android:id="@+id/upload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload" />
<TextView
android:id="@+id/filename1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="FileName 1: " />
<TextView
android:id="@+id/filename2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="FileName 2: " />
<Button
android:id="@+id/uploadMultiple"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Upload Multiple" />
</LinearLayout>
</ScrollView>
Function to upload file:
// Uploading Image/Video
private void uploadFile() {
progressDialog.show();
// Map is used to multipart the file using okhttp3.RequestBody File file = new File(mediaPath);
// Parsing any Media type file RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call call = getResponse.uploadFile(fileToUpload, filename);
call.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
}
} else {
assert serverResponse != null;
Log.v("Response", serverResponse.toString());
}
progressDialog.dismiss();
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
}
Upload Multiple Files
Create a PHP file named as upload_multiple_files.php and paste the following lines.
<?php
$target_dir = "uploads/";
$target_file_name1 = $target_dir.basename($_FILES["file1"]["name"]);
$target_file_name2 = $target_dir.basename($_FILES["file2"]["name"]);
$response = array();
// Check if image file is a actual image or fake image
if (isset($_FILES["file1"])&&isset($_FILES["file2"]))
{
if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file_name1)
&& move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file_name2))
{
$success = true;
$message = "Successfully Uploaded";
}
else
{
$success = false;
$message = "Error while uploading";
}
}
else
{
$success = false;
$message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);
?>
Function to upload multiple file:
Add the following code to upload multiple files in your activity/fragment// Uploading Image/Video
private void uploadMultipleFiles() {
progressDialog.show();
// Map is used to multipart the file using okhttp3.RequestBody
File file = new File(mediaPath);
File file1 = new File(mediaPath1);
// Parsing any Media type file
RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);
RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);
MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file.getName(), requestBody1);
MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<serverresponse> call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);
call.enqueue(new Callback<serverresponse>() {
@Override
public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
assert serverResponse != null;
Log.v("Response", serverResponse.toString());
}
progressDialog.dismiss();
}
@Override
public void onFailure(Call<serverresponse> call, Throwable t) {
}
});
}
ApiConfig.javaAdd the following interface for uploading multiple files in ApiConfig.java
@Multipart
@POST("retrofit_example/upload_multiple_files.php")
Call <serverresponse> uploadMulFile(@Part MultipartBody.Part file1, @Part MultipartBody.Part file2);
Full Source Code
Create MainActivity.java and Paste the following linespublic class MainActivity extends AppCompatActivity {
Button btnUpload, btnMulUpload, btnPickImage, btnPickVideo;
String mediaPath, mediaPath1;
ImageView imgView;
String[] mediaColumns = {MediaStore.Video.Media._ID};
ProgressDialog progressDialog;
TextView str1, str2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Uploading...");
btnUpload = (Button) findViewById(R.id.upload);
btnMulUpload = (Button) findViewById(R.id.uploadMultiple);
btnPickImage = (Button) findViewById(R.id.pick_img);
btnPickVideo = (Button) findViewById(R.id.pick_vdo);
imgView = (ImageView) findViewById(R.id.preview);
str1 = (TextView) findViewById(R.id.filename1);
str2 = (TextView) findViewById(R.id.filename2);
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadFile();
}
});
btnMulUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadMultipleFiles();
}
});
btnPickImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 0);
}
});
// Video must be low in Memory or need to be compressed before uploading...
btnPickVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == 0 && resultCode == RESULT_OK && null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
str1.setText(mediaPath);
// Set the Image in ImageView for Previewing the Media
imgView.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
cursor.close();
} // When an Video is picked
else if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
// Get the Video from data
Uri selectedVideo = data.getData();
String[] filePathColumn = {MediaStore.Video.Media.DATA};
Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath1 = cursor.getString(columnIndex);
str2.setText(mediaPath1);
// Set the Video Thumb in ImageView Previewing the Media
imgView.setImageBitmap(getThumbnailPathForLocalFile(MainActivity.this, selectedVideo));
cursor.close();
} else {
Toast.makeText(this, "You haven't picked Image/Video", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
// Providing Thumbnail For Selected Image
public Bitmap getThumbnailPathForLocalFile(Activity context, Uri fileUri) {
long fileId = getFileId(context, fileUri);
return MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
fileId, MediaStore.Video.Thumbnails.MICRO_KIND, null);
}
// Getting Selected File ID
public long getFileId(Activity context, Uri fileUri) {
Cursor cursor = context.managedQuery(fileUri, mediaColumns, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
return cursor.getInt(columnIndex);
}
return 0;
}
// Uploading Image/Video
private void uploadFile() {
progressDialog.show();
// Map is used to multipart the file using okhttp3.RequestBody
File file = new File(mediaPath);
// Parsing any Media type file
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<serverresponse> call = getResponse.uploadFile(fileToUpload, filename);
call.enqueue(new Callback<serverresponse>() {
@Override
public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
assert serverResponse != null;
Log.v("Response", serverResponse.toString());
}
progressDialog.dismiss();
}
@Override
public void onFailure(Call<serverresponse> call, Throwable t) {
}
});
}
// Uploading Image/Video
private void uploadMultipleFiles() {
progressDialog.show();
// Map is used to multipart the file using okhttp3.RequestBody
File file = new File(mediaPath);
File file1 = new File(mediaPath1);
// Parsing any Media type file
RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);
RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);
MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file.getName(), requestBody1);
MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<serverresponse> call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);
call.enqueue(new Callback() {
@Override
public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
assert serverResponse != null;
Log.v("Response", serverResponse.toString());
}
progressDialog.dismiss();
}
@Override
public void onFailure(Call<serverresponse> call, Throwable t) {
}
});
}
}
Download Code:
You can download the full source from the following Github link. If you Like this tutorial, Please star it in Github.Post your doubts and comments in the comments section.
Thank you
ReplyDeleteworked for u
DeleteNOT WORKING-WHENEVER I SELECT VIDEO IT SHOWS SOMTHING WENT WRONG,AND WHENEVER SELECT IMAGE IT DOES NOT SELECT IMAGE BUT DOES NOT VIEW IN IMAGE VIEW AND WHEN I PRESS UPLOAD BUTTON IT JUST SHOWS PROGRESS NOTHING ELSE
ReplyDeleteNOW THIS NEW ERROR
ReplyDelete08-11 11:20:50.284 18045-18045/com.saeed.lastretrofitvideo V/ActivityThread: updateVisibility : ActivityRecord{747ddb5 token=android.os.BinderProxy@9333a3e {com.saeed.lastretrofitvideo/com.saeed.lastretrofitvideo.MainActivity}} show : false
Hi plz follow the proper scenario. This wont work. Its just a basic things
DeleteHi Saeed,
DeleteIt is worked for me perfectly
It happens because of Timeout in Server
ReplyDeleteI tried your code. But actually it does not reach upto php file. and response will be null. what to do now?
ReplyDeletewhat about pdf files ?
ReplyDeletePossible But timeout may happen due to its size
DeleteHello its nice Tutorial.
ReplyDeleteCan you show me the exact url which you are using in this example
I Already Provided the PHP File above
ReplyDeleteIs this php file work.... Its not proper guide mustaq. Plz update this. Not having basic structure of the php
DeletePlease provide code upload all type of files.
ReplyDeleteIf u want convert all files plz encode the file based on its type. Refer how to encode the file type. U need to handle time out exception also which provided by google.
Deletehow can i pass other params like email,bday etc in this example.
ReplyDeleteexplain briefly please
DeleteVeryy GOOD :)))
ReplyDeleteThankss
How multiple images
Thanks Bro, for your support.
DeleteI updated the post with Multiple File Upload using Retrofit
Link to Upload Multiple Files
How can the progress of the upload be shown in percentage? Your code worked.
ReplyDeletehi good script work perfect thx
ReplyDeletebut now i need to pass an extra parameter for sub directory
uploads/"extra parameter"/filename
how can i do this
Great awesome tutorial !
ReplyDeleteI have run itu successfully, if I wanna upload with mysql query, which code is must replace in php file or android class?
Thank You, its great, everything works well, but how can I change source directory (for example Environment.getExternalStorageDirectory() + "/some_dir/"), when I want to upload *.txt files...? Thanks, Ivo
ReplyDeleteIts not working for the video any soln
ReplyDeletevideo upload not working bro
ReplyDeleteWow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed.
ReplyDeletesplit pdf into multiple files online
Thanks for sharing this useful info..
ReplyDeletejava代做
Incredible new multicam support. Ground-breaking keying highlights. Supports Thunderbolt and studio-screen yield.
ReplyDeleteAnyConv
Visual depiction is a quickly developing industry that requires a great deal of aptitudes from workers. Professional graphic design
ReplyDeleteIt is showing Error while uploading
ReplyDelete