├── Android-File-Upload-Tutorial
├── .gitignore
├── app
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src
│ │ ├── androidTest
│ │ └── java
│ │ │ └── com
│ │ │ └── hellohasan
│ │ │ └── android_file_upload_tutorial
│ │ │ └── ExampleInstrumentedTest.java
│ │ ├── main
│ │ ├── AndroidManifest.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── hellohasan
│ │ │ │ └── android_file_upload_tutorial
│ │ │ │ ├── MainActivity.java
│ │ │ │ ├── ModelClass
│ │ │ │ ├── EventModel.java
│ │ │ │ ├── ImageSenderInfo.java
│ │ │ │ └── ResponseModel.java
│ │ │ │ └── NetworkRelatedClass
│ │ │ │ ├── ApiInterface.java
│ │ │ │ ├── NetworkCall.java
│ │ │ │ └── RetrofitApiClient.java
│ │ └── res
│ │ │ ├── layout
│ │ │ └── activity_main.xml
│ │ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ └── values
│ │ │ ├── colors.xml
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ │ └── test
│ │ └── java
│ │ └── com
│ │ └── hellohasan
│ │ └── android_file_upload_tutorial
│ │ └── ExampleUnitTest.java
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
├── Data
└── image-upload-to-server-android-retrofit.gif
├── README.md
└── file_upload_api
├── files
└── images (1).jpeg
└── upload.php
/Android-File-Upload-Tutorial/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea
5 | .DS_Store
6 | /build
7 | /captures
8 | .externalNativeBuild
9 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | android {
4 | compileSdkVersion 28
5 | defaultConfig {
6 | applicationId "com.hellohasan.android_file_upload_tutorial"
7 | minSdkVersion 15
8 | targetSdkVersion 28
9 | versionCode 1
10 | versionName "1.0"
11 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
12 | }
13 | buildTypes {
14 | release {
15 | minifyEnabled false
16 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
17 | }
18 | }
19 | compileOptions {
20 | sourceCompatibility JavaVersion.VERSION_1_8
21 | targetCompatibility JavaVersion.VERSION_1_8
22 | }
23 | }
24 |
25 | dependencies {
26 | implementation fileTree(dir: 'libs', include: ['*.jar'])
27 | androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', {
28 | exclude group: 'com.android.support', module: 'support-annotations'
29 | })
30 | implementation 'androidx.appcompat:appcompat:1.1.0'
31 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
32 | testImplementation 'junit:junit:4.12'
33 |
34 | // networking library
35 | implementation 'com.squareup.okhttp3:okhttp:3.14.2'
36 | implementation 'com.squareup.retrofit2:retrofit:2.5.0'
37 | implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
38 |
39 | // JSON parsing, serialize-deserialize
40 | implementation 'com.google.code.gson:gson:2.8.6'
41 |
42 | // pretty logger
43 | implementation 'com.orhanobut:logger:2.2.0'
44 |
45 | // image loading and caching
46 | implementation 'com.squareup.picasso:picasso:2.71828'
47 |
48 | // event publish/subscribe
49 | implementation 'org.greenrobot:eventbus:3.1.1'
50 | }
51 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /home/hasan/Android/Sdk/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
12 | # If your project uses WebView with JS, uncomment the following
13 | # and specify the fully qualified class name to the JavaScript interface
14 | # class:
15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
16 | # public *;
17 | #}
18 |
19 | # Uncomment this to preserve the line number information for
20 | # debugging stack traces.
21 | #-keepattributes SourceFile,LineNumberTable
22 |
23 | # If you keep the line number information, uncomment this to
24 | # hide the original source file name.
25 | #-renamesourcefileattribute SourceFile
26 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/androidTest/java/com/hellohasan/android_file_upload_tutorial/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.hellohasan.android_file_upload_tutorial;
2 |
3 | import android.content.Context;
4 | import androidx.test.platform.app.InstrumentationRegistry;
5 | import androidx.test.ext.junit.runners.AndroidJUnit4;
6 |
7 | import org.junit.Test;
8 | import org.junit.runner.RunWith;
9 |
10 | import static org.junit.Assert.*;
11 |
12 | /**
13 | * Instrumentation test, which will execute on an Android device.
14 | *
15 | * @see Testing documentation
16 | */
17 | @RunWith(AndroidJUnit4.class)
18 | public class ExampleInstrumentedTest {
19 | @Test
20 | public void useAppContext() throws Exception {
21 | // Context of the app under test.
22 | Context appContext = InstrumentationRegistry.getTargetContext();
23 |
24 | assertEquals("com.hellohasan.android_file_upload_tutorial", appContext.getPackageName());
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/java/com/hellohasan/android_file_upload_tutorial/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.hellohasan.android_file_upload_tutorial;
2 |
3 | import android.Manifest;
4 | import android.app.Activity;
5 | import android.content.Intent;
6 | import android.content.pm.PackageManager;
7 | import android.database.Cursor;
8 | import android.net.Uri;
9 | import android.os.Bundle;
10 | import android.provider.MediaStore;
11 | import androidx.core.app.ActivityCompat;
12 | import androidx.appcompat.app.AppCompatActivity;
13 | import android.view.View;
14 | import android.widget.Button;
15 | import android.widget.EditText;
16 | import android.widget.ImageView;
17 | import android.widget.TextView;
18 |
19 | import com.hellohasan.android_file_upload_tutorial.ModelClass.EventModel;
20 | import com.hellohasan.android_file_upload_tutorial.ModelClass.ImageSenderInfo;
21 | import com.hellohasan.android_file_upload_tutorial.NetworkRelatedClass.NetworkCall;
22 |
23 | import org.greenrobot.eventbus.EventBus;
24 | import org.greenrobot.eventbus.Subscribe;
25 | import org.greenrobot.eventbus.ThreadMode;
26 |
27 | public class MainActivity extends AppCompatActivity {
28 |
29 | // if you want to upload only image, make it true. Otherwise to allow any file- false
30 | boolean isOnlyImageAllowed = true;
31 |
32 | private EditText nameEditText;
33 | private EditText ageEditText;
34 | private ImageView imageView;
35 | private Button uploadButton;
36 | private TextView responseTextView;
37 |
38 | private String filePath;
39 | private static final int PICK_PHOTO = 1958;
40 | private static final int REQUEST_EXTERNAL_STORAGE = 1;
41 | private static String[] PERMISSIONS_STORAGE = {
42 | Manifest.permission.WRITE_EXTERNAL_STORAGE
43 | };
44 |
45 | @Subscribe(threadMode = ThreadMode.MAIN)
46 | public void onEvent(EventModel event) throws ClassNotFoundException {
47 | if (event.isTagMatchWith("response")) {
48 | String responseMessage = "Response from Server:\n" + event.getMessage();
49 | responseTextView.setText(responseMessage);
50 | }
51 | }
52 |
53 | @Override
54 | protected void onCreate(Bundle savedInstanceState) {
55 | super.onCreate(savedInstanceState);
56 | setContentView(R.layout.activity_main);
57 |
58 | nameEditText = findViewById(R.id.nameEditText);
59 | ageEditText = findViewById(R.id.ageEditText);
60 | imageView = findViewById(R.id.imageView);
61 | uploadButton = findViewById(R.id.uploadButton);
62 | responseTextView = findViewById(R.id.responseTextView);
63 |
64 | verifyStoragePermissions(this);
65 | }
66 |
67 | public void addPhoto(View view) {
68 |
69 | Intent intent;
70 |
71 | if (isOnlyImageAllowed) {
72 | // only image can be selected
73 | intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
74 | } else {
75 | // any type of files including image can be selected
76 | intent = new Intent(Intent.ACTION_GET_CONTENT);
77 | intent.setType("file/*");
78 | }
79 |
80 | startActivityForResult(intent, PICK_PHOTO);
81 | }
82 |
83 | @Override
84 | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
85 | super.onActivityResult(requestCode, resultCode, data);
86 | if (resultCode == RESULT_OK && requestCode == PICK_PHOTO) {
87 | Uri imageUri = data.getData();
88 | filePath = getPath(imageUri);
89 | imageView.setImageURI(imageUri);
90 | uploadButton.setVisibility(View.VISIBLE);
91 | }
92 | }
93 |
94 | public void uploadButtonClicked(View view) {
95 | String name = nameEditText.getText().toString();
96 | int age = Integer.parseInt(ageEditText.getText().toString());
97 | NetworkCall.fileUpload(filePath, new ImageSenderInfo(name, age));
98 | }
99 |
100 | private String getPath(Uri uri) {
101 | String[] projection = { MediaStore.Images.Media.DATA };
102 | Cursor cursor = managedQuery(uri, projection, null, null, null);
103 | int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
104 | cursor.moveToFirst();
105 | return cursor.getString(column_index);
106 | }
107 |
108 | @Override
109 | public void onStart() {
110 | super.onStart();
111 | EventBus.getDefault().register(this);
112 | }
113 |
114 | @Override
115 | public void onStop() {
116 | EventBus.getDefault().unregister(this);
117 | super.onStop();
118 | }
119 |
120 | /**
121 | * Checks if the app has permission to write to device storage
122 | *
123 | * If the app does not has permission then the user will be prompted to grant permissions
124 | */
125 | public static void verifyStoragePermissions(Activity activity) {
126 | // Check if we have write permission
127 | int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
128 |
129 | if (permission != PackageManager.PERMISSION_GRANTED) {
130 | // We don't have permission so prompt the user
131 | ActivityCompat.requestPermissions(
132 | activity,
133 | PERMISSIONS_STORAGE,
134 | REQUEST_EXTERNAL_STORAGE
135 | );
136 | }
137 | }
138 | }
139 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/java/com/hellohasan/android_file_upload_tutorial/ModelClass/EventModel.java:
--------------------------------------------------------------------------------
1 | package com.hellohasan.android_file_upload_tutorial.ModelClass;
2 |
3 | public class EventModel {
4 | private String eventTag;
5 | private String message;
6 |
7 | public EventModel(String eventTag, String message) {
8 | this.eventTag = eventTag;
9 | this.message = message;
10 | }
11 |
12 | public boolean isTagMatchWith(String tag){
13 | return eventTag.equals(tag);
14 | }
15 |
16 | public String getMessage() {
17 | return message;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/java/com/hellohasan/android_file_upload_tutorial/ModelClass/ImageSenderInfo.java:
--------------------------------------------------------------------------------
1 |
2 | package com.hellohasan.android_file_upload_tutorial.ModelClass;
3 |
4 | import android.os.Parcel;
5 | import android.os.Parcelable;
6 |
7 | import com.google.gson.annotations.SerializedName;
8 |
9 | public class ImageSenderInfo implements Parcelable {
10 |
11 | @SerializedName("sender_name")
12 | private String sender;
13 | @SerializedName("sender_age")
14 | private int age;
15 |
16 | public ImageSenderInfo() {
17 | }
18 |
19 | public ImageSenderInfo(String sender, int age) {
20 | this.sender = sender;
21 | this.age = age;
22 | }
23 |
24 | public final static Parcelable.Creator CREATOR = new Creator() {
25 |
26 | @SuppressWarnings({
27 | "unchecked"
28 | })
29 | public ImageSenderInfo createFromParcel(Parcel in) {
30 | ImageSenderInfo instance = new ImageSenderInfo();
31 | instance.sender = ((String) in.readValue((String.class.getClassLoader())));
32 | instance.age = ((int) in.readValue((int.class.getClassLoader())));
33 | return instance;
34 | }
35 |
36 | public ImageSenderInfo[] newArray(int size) {
37 | return (new ImageSenderInfo[size]);
38 | }
39 |
40 | };
41 |
42 |
43 | public void writeToParcel(Parcel dest, int flags) {
44 | dest.writeValue(sender);
45 | dest.writeValue(age);
46 | }
47 |
48 | public int describeContents() {
49 | return 0;
50 | }
51 |
52 | }
53 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/java/com/hellohasan/android_file_upload_tutorial/ModelClass/ResponseModel.java:
--------------------------------------------------------------------------------
1 |
2 | package com.hellohasan.android_file_upload_tutorial.ModelClass;
3 |
4 | import android.os.Parcel;
5 | import android.os.Parcelable;
6 |
7 | import com.google.gson.annotations.SerializedName;
8 |
9 | public class ResponseModel implements Parcelable
10 | {
11 |
12 | @SerializedName("success")
13 | private boolean success;
14 | @SerializedName("message")
15 | private String message;
16 | public final static Parcelable.Creator CREATOR = new Creator() {
17 |
18 |
19 | @SuppressWarnings({
20 | "unchecked"
21 | })
22 | public ResponseModel createFromParcel(Parcel in) {
23 | ResponseModel instance = new ResponseModel();
24 | instance.success = ((boolean) in.readValue((boolean.class.getClassLoader())));
25 | instance.message = ((String) in.readValue((String.class.getClassLoader())));
26 | return instance;
27 | }
28 |
29 | public ResponseModel[] newArray(int size) {
30 | return (new ResponseModel[size]);
31 | }
32 |
33 | };
34 |
35 | /**
36 | *
37 | * @return
38 | * The success
39 | */
40 | public boolean isSuccess() {
41 | return success;
42 | }
43 |
44 | /**
45 | *
46 | * @return
47 | * The message
48 | */
49 | public String getMessage() {
50 | return message;
51 | }
52 |
53 |
54 | public void writeToParcel(Parcel dest, int flags) {
55 | dest.writeValue(success);
56 | dest.writeValue(message);
57 | }
58 |
59 | public int describeContents() {
60 | return 0;
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/java/com/hellohasan/android_file_upload_tutorial/NetworkRelatedClass/ApiInterface.java:
--------------------------------------------------------------------------------
1 | package com.hellohasan.android_file_upload_tutorial.NetworkRelatedClass;
2 |
3 | import com.hellohasan.android_file_upload_tutorial.ModelClass.ResponseModel;
4 |
5 | import okhttp3.MultipartBody;
6 | import okhttp3.RequestBody;
7 | import retrofit2.Call;
8 | import retrofit2.http.Multipart;
9 | import retrofit2.http.POST;
10 | import retrofit2.http.Part;
11 |
12 |
13 | public interface ApiInterface {
14 |
15 | @Multipart
16 | @POST("file_upload_api/upload.php")
17 | Call fileUpload(
18 | @Part("sender_information") RequestBody description,
19 | @Part MultipartBody.Part file);
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/java/com/hellohasan/android_file_upload_tutorial/NetworkRelatedClass/NetworkCall.java:
--------------------------------------------------------------------------------
1 | package com.hellohasan.android_file_upload_tutorial.NetworkRelatedClass;
2 |
3 | import androidx.annotation.NonNull;
4 |
5 | import com.google.gson.Gson;
6 | import com.hellohasan.android_file_upload_tutorial.ModelClass.EventModel;
7 | import com.hellohasan.android_file_upload_tutorial.ModelClass.ImageSenderInfo;
8 | import com.hellohasan.android_file_upload_tutorial.ModelClass.ResponseModel;
9 | import com.orhanobut.logger.AndroidLogAdapter;
10 | import com.orhanobut.logger.Logger;
11 |
12 | import org.greenrobot.eventbus.EventBus;
13 |
14 | import java.io.File;
15 |
16 | import okhttp3.MediaType;
17 | import okhttp3.MultipartBody;
18 | import okhttp3.RequestBody;
19 | import retrofit2.Call;
20 | import retrofit2.Callback;
21 | import retrofit2.Response;
22 |
23 | public class NetworkCall {
24 |
25 | public static void fileUpload(String filePath, ImageSenderInfo imageSenderInfo) {
26 |
27 | ApiInterface apiInterface = RetrofitApiClient.getClient().create(ApiInterface.class);
28 | Logger.addLogAdapter(new AndroidLogAdapter());
29 |
30 | File file = new File(filePath);
31 | //create RequestBody instance from file
32 | RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file); //allow image and any other file
33 |
34 | // MultipartBody.Part is used to send also the actual file name
35 | MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
36 |
37 | Gson gson = new Gson();
38 | String patientData = gson.toJson(imageSenderInfo);
39 |
40 | RequestBody description = RequestBody.create(okhttp3.MultipartBody.FORM, patientData);
41 |
42 | // finally, execute the request
43 | Call call = apiInterface.fileUpload(description, body);
44 | call.enqueue(new Callback() {
45 | @Override
46 | public void onResponse(@NonNull Call call, @NonNull Response response) {
47 | Logger.d("Response: " + response);
48 |
49 | ResponseModel responseModel = response.body();
50 |
51 | if(responseModel != null){
52 | EventBus.getDefault().post(new EventModel("response", responseModel.getMessage()));
53 | Logger.d("Response code " + response.code() +
54 | " Response Message: " + responseModel.getMessage());
55 | } else
56 | EventBus.getDefault().post(new EventModel("response", "ResponseModel is NULL"));
57 | }
58 |
59 | @Override
60 | public void onFailure(@NonNull Call call, @NonNull Throwable t) {
61 | Logger.d("Exception: " + t);
62 | EventBus.getDefault().post(new EventModel("response", t.getMessage()));
63 | }
64 | });
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/java/com/hellohasan/android_file_upload_tutorial/NetworkRelatedClass/RetrofitApiClient.java:
--------------------------------------------------------------------------------
1 | package com.hellohasan.android_file_upload_tutorial.NetworkRelatedClass;
2 |
3 | import com.google.gson.Gson;
4 | import com.google.gson.GsonBuilder;
5 |
6 | import java.util.concurrent.TimeUnit;
7 |
8 | import okhttp3.OkHttpClient;
9 | import retrofit2.Retrofit;
10 | import retrofit2.converter.gson.GsonConverterFactory;
11 |
12 | public class RetrofitApiClient {
13 |
14 | private static final String BASE_URL = "http://192.168.43.55/"; //IP of your localhost or live server
15 |
16 | private static Retrofit retrofit = null;
17 |
18 | private static Gson gson = new GsonBuilder()
19 | .setLenient()
20 | .create();
21 |
22 | private RetrofitApiClient() {} // So that nobody can create an object with constructor
23 |
24 | public static synchronized Retrofit getClient() {
25 | if (retrofit==null) {
26 |
27 | int timeOut = 5 * 60;
28 | OkHttpClient client = new OkHttpClient.Builder()
29 | .connectTimeout(timeOut, TimeUnit.SECONDS)
30 | .writeTimeout(timeOut, TimeUnit.SECONDS)
31 | .readTimeout(timeOut, TimeUnit.SECONDS)
32 | .build();
33 |
34 | retrofit = new Retrofit.Builder()
35 | .baseUrl(BASE_URL)
36 | .addConverterFactory(GsonConverterFactory.create(gson))
37 | .client(client)
38 | .build();
39 | }
40 | return retrofit;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
9 |
10 |
18 |
19 |
28 |
29 |
42 |
43 |
53 |
54 |
63 |
64 |
73 |
74 |
75 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #3F51B5
4 | #303F9F
5 | #FF4081
6 |
7 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | File Uploader
3 |
4 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/app/src/test/java/com/hellohasan/android_file_upload_tutorial/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.hellohasan.android_file_upload_tutorial;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() throws Exception {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | repositories {
5 | jcenter()
6 | google()
7 | }
8 | dependencies {
9 | classpath 'com.android.tools.build:gradle:3.5.2'
10 |
11 | // NOTE: Do not place your application dependencies here; they belong
12 | // in the individual module build.gradle files
13 | }
14 | }
15 |
16 | allprojects {
17 | repositories {
18 | jcenter()
19 | google()
20 | }
21 | }
22 |
23 | task clean(type: Delete) {
24 | delete rootProject.buildDir
25 | }
26 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | android.enableJetifier=true
13 | android.useAndroidX=true
14 | org.gradle.jvmargs=-Xmx1536m
15 |
16 | # When configured, Gradle will run in incubating parallel mode.
17 | # This option should only be used with decoupled projects. More details, visit
18 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
19 | # org.gradle.parallel=true
20 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Android-File-Upload-Tutorial/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Tue Oct 29 17:22:52 BDT 2019
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
7 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
10 | DEFAULT_JVM_OPTS=""
11 |
12 | APP_NAME="Gradle"
13 | APP_BASE_NAME=`basename "$0"`
14 |
15 | # Use the maximum available, or set MAX_FD != -1 to use that value.
16 | MAX_FD="maximum"
17 |
18 | warn ( ) {
19 | echo "$*"
20 | }
21 |
22 | die ( ) {
23 | echo
24 | echo "$*"
25 | echo
26 | exit 1
27 | }
28 |
29 | # OS specific support (must be 'true' or 'false').
30 | cygwin=false
31 | msys=false
32 | darwin=false
33 | case "`uname`" in
34 | CYGWIN* )
35 | cygwin=true
36 | ;;
37 | Darwin* )
38 | darwin=true
39 | ;;
40 | MINGW* )
41 | msys=true
42 | ;;
43 | esac
44 |
45 | # Attempt to set APP_HOME
46 | # Resolve links: $0 may be a link
47 | PRG="$0"
48 | # Need this for relative symlinks.
49 | while [ -h "$PRG" ] ; do
50 | ls=`ls -ld "$PRG"`
51 | link=`expr "$ls" : '.*-> \(.*\)$'`
52 | if expr "$link" : '/.*' > /dev/null; then
53 | PRG="$link"
54 | else
55 | PRG=`dirname "$PRG"`"/$link"
56 | fi
57 | done
58 | SAVED="`pwd`"
59 | cd "`dirname \"$PRG\"`/" >/dev/null
60 | APP_HOME="`pwd -P`"
61 | cd "$SAVED" >/dev/null
62 |
63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
64 |
65 | # Determine the Java command to use to start the JVM.
66 | if [ -n "$JAVA_HOME" ] ; then
67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
68 | # IBM's JDK on AIX uses strange locations for the executables
69 | JAVACMD="$JAVA_HOME/jre/sh/java"
70 | else
71 | JAVACMD="$JAVA_HOME/bin/java"
72 | fi
73 | if [ ! -x "$JAVACMD" ] ; then
74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
75 |
76 | Please set the JAVA_HOME variable in your environment to match the
77 | location of your Java installation."
78 | fi
79 | else
80 | JAVACMD="java"
81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
82 |
83 | Please set the JAVA_HOME variable in your environment to match the
84 | location of your Java installation."
85 | fi
86 |
87 | # Increase the maximum file descriptors if we can.
88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
89 | MAX_FD_LIMIT=`ulimit -H -n`
90 | if [ $? -eq 0 ] ; then
91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
92 | MAX_FD="$MAX_FD_LIMIT"
93 | fi
94 | ulimit -n $MAX_FD
95 | if [ $? -ne 0 ] ; then
96 | warn "Could not set maximum file descriptor limit: $MAX_FD"
97 | fi
98 | else
99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
100 | fi
101 | fi
102 |
103 | # For Darwin, add options to specify how the application appears in the dock
104 | if $darwin; then
105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
106 | fi
107 |
108 | # For Cygwin, switch paths to Windows format before running java
109 | if $cygwin ; then
110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
112 | JAVACMD=`cygpath --unix "$JAVACMD"`
113 |
114 | # We build the pattern for arguments to be converted via cygpath
115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
116 | SEP=""
117 | for dir in $ROOTDIRSRAW ; do
118 | ROOTDIRS="$ROOTDIRS$SEP$dir"
119 | SEP="|"
120 | done
121 | OURCYGPATTERN="(^($ROOTDIRS))"
122 | # Add a user-defined pattern to the cygpath arguments
123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
125 | fi
126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
127 | i=0
128 | for arg in "$@" ; do
129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
131 |
132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
134 | else
135 | eval `echo args$i`="\"$arg\""
136 | fi
137 | i=$((i+1))
138 | done
139 | case $i in
140 | (0) set -- ;;
141 | (1) set -- "$args0" ;;
142 | (2) set -- "$args0" "$args1" ;;
143 | (3) set -- "$args0" "$args1" "$args2" ;;
144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
150 | esac
151 | fi
152 |
153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
154 | function splitJvmOpts() {
155 | JVM_OPTS=("$@")
156 | }
157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
159 |
160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
161 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
12 | set DEFAULT_JVM_OPTS=
13 |
14 | set DIRNAME=%~dp0
15 | if "%DIRNAME%" == "" set DIRNAME=.
16 | set APP_BASE_NAME=%~n0
17 | set APP_HOME=%DIRNAME%
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windowz variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 | if "%@eval[2+2]" == "4" goto 4NT_args
53 |
54 | :win9xME_args
55 | @rem Slurp the command line arguments.
56 | set CMD_LINE_ARGS=
57 | set _SKIP=2
58 |
59 | :win9xME_args_slurp
60 | if "x%~1" == "x" goto execute
61 |
62 | set CMD_LINE_ARGS=%*
63 | goto execute
64 |
65 | :4NT_args
66 | @rem Get arguments from the 4NT Shell from JP Software
67 | set CMD_LINE_ARGS=%$
68 |
69 | :execute
70 | @rem Setup the command line
71 |
72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if "%ERRORLEVEL%"=="0" goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
85 | exit /b 1
86 |
87 | :mainEnd
88 | if "%OS%"=="Windows_NT" endlocal
89 |
90 | :omega
91 |
--------------------------------------------------------------------------------
/Android-File-Upload-Tutorial/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 |
--------------------------------------------------------------------------------
/Data/image-upload-to-server-android-retrofit.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/Data/image-upload-to-server-android-retrofit.gif
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Image or any File Upload to Server using Retrofit in Android App
2 |
3 | We'll design this type of sample Android App using [Retrofit](https://github.com/square/retrofit) Android Library:
4 |
5 |
6 |
7 | Create instance of `Retrofit` class (You can check basic Retrofit implementation from [here](https://github.com/hasancse91/retrofit-implementation))
8 | ```java
9 | public class RetrofitApiClient {
10 |
11 | private static final String BASE_URL = "http://yourdomainname.com"; //I used IP of my local machine
12 |
13 | private static Retrofit retrofit = null;
14 |
15 | private static Gson gson = new GsonBuilder()
16 | .setLenient()
17 | .create();
18 |
19 | private RetrofitApiClient() {} // So that nobody can create an object with constructor
20 |
21 | public static synchronized Retrofit getClient() {
22 | if (retrofit==null) {
23 |
24 | int timeOut = 5 * 60;
25 | OkHttpClient client = new OkHttpClient.Builder()
26 | .connectTimeout(timeOut, TimeUnit.SECONDS)
27 | .writeTimeout(timeOut, TimeUnit.SECONDS)
28 | .readTimeout(timeOut, TimeUnit.SECONDS)
29 | .build();
30 |
31 | retrofit = new Retrofit.Builder()
32 | .baseUrl(BASE_URL)
33 | .addConverterFactory(GsonConverterFactory.create(gson))
34 | .client(client)
35 | .build();
36 | }
37 | return retrofit;
38 | }
39 | }
40 | ```
41 |
42 | The `Interface` class is given below:
43 | ```java
44 | public interface ApiInterface {
45 |
46 | @Multipart
47 | @POST("file_upload_api/upload.php")
48 | Call fileUpload(
49 | @Part("sender_information") RequestBody description,
50 | @Part MultipartBody.Part file);
51 | }
52 | ```
53 |
54 | File upload method is here:
55 | ```java
56 | public static void fileUpload(String filePath, ImageSenderInfo imageSenderInfo) {
57 |
58 | ApiInterface apiInterface = RetrofitApiClient.getClient().create(ApiInterface.class);
59 | Logger.addLogAdapter(new AndroidLogAdapter());
60 |
61 | File file = new File(filePath);
62 | //create RequestBody instance from file
63 | RequestBody requestFile = RequestBody.create(MediaType.parse("image"), file);
64 |
65 | // MultipartBody.Part is used to send also the actual file name
66 | MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
67 |
68 | Gson gson = new Gson();
69 | String patientData = gson.toJson(imageSenderInfo);
70 |
71 | RequestBody description = RequestBody.create(okhttp3.MultipartBody.FORM, patientData);
72 |
73 | // finally, execute the request
74 | Call call = apiInterface.fileUpload(description, body);
75 | call.enqueue(new Callback() {
76 | @Override
77 | public void onResponse(@NonNull Call call, @NonNull Response response) {
78 | Logger.d("Response: " + response);
79 |
80 | ResponseModel responseModel = response.body();
81 |
82 | if(responseModel != null){
83 | EventBus.getDefault().post(new EventModel("response", responseModel.getMessage()));
84 | Logger.d("Response code " + response.code() +
85 | " Response Message: " + responseModel.getMessage());
86 | } else
87 | EventBus.getDefault().post(new EventModel("response", "ResponseModel is NULL"));
88 | }
89 |
90 | @Override
91 | public void onFailure(@NonNull Call call, @NonNull Throwable t) {
92 | Logger.d("Exception: " + t);
93 | EventBus.getDefault().post(new EventModel("response", t.getMessage()));
94 | }
95 | });
96 | }
97 | ```
98 | Here I used [EventBus](https://github.com/greenrobot/EventBus) Library to notify my UI from a different class. The simple implementation of `EventBus` is given [here](https://github.com/hasancse91/EventBus-Android-Tutorial).
99 |
100 | I used my local machine as a server (localhost). To do so, I created a folder `file_upload_api` in my `www>html` folder (for Linux). Inside this folder I created a folder `files`. This folder will contain my uploaded images. Then put a `PHP` script as a sibling of `files` folder. Here I mention the `upload.php` code:
101 |
102 | ```php
103 | false, 'message' => 'Sorry, there was an error uploading your file.');
108 |
109 | $data = $_POST['sender_information'];
110 | $json_data = json_decode($data , true);
111 | $sender_name = $json_data['sender_name'];
112 | $sender_age = $json_data['sender_age'];
113 |
114 |
115 | if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
116 | $response = array('success' => true, 'message' => 'Hello '.$sender_name.'! You are '.$sender_age.' years old. Your image is uploaded successfully!');
117 |
118 | echo json_encode($response);
119 | ?>
120 | ```
121 | ### Disclaimer
122 | This `PHP` script cannot handle a large file. If you upload a tiny image it'll work fine. But for any large image you'll get error message. To upload large image file please search on Google.
123 |
--------------------------------------------------------------------------------
/file_upload_api/files/images (1).jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/hasancse91/Android-File-Upload-To-Server/44de3d7d333e91b7f76a6e073f6e7bd79afd06b6/file_upload_api/files/images (1).jpeg
--------------------------------------------------------------------------------
/file_upload_api/upload.php:
--------------------------------------------------------------------------------
1 | false, 'message' => 'Sorry, there was an error uploading your file.');
6 |
7 | $data = $_POST['sender_information'];
8 | $json_data = json_decode($data , true);
9 | $sender_name = $json_data['sender_name'];
10 | $sender_age = $json_data['sender_age'];
11 |
12 |
13 | if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
14 | $response = array('success' => true, 'message' => 'Hello '.$sender_name.'! You are '.$sender_age.' years old. Your image is uploaded successfully!');
15 |
16 | echo json_encode($response);
17 | ?>
18 |
--------------------------------------------------------------------------------