Giter Site home page Giter Site logo

nguyenngan / android-file-upload-to-server Goto Github PK

View Code? Open in Web Editor NEW

This project forked from hasancse91/android-file-upload-to-server

0.0 1.0 0.0 1.34 MB

Check my Bengali tutorial post of Android File Upload service from this URL

Home Page: https://hellohasan.com/2017/08/13/image-file-upload-retrofit-android/

Java 94.68% PHP 5.32%

android-file-upload-to-server's Introduction

Image or any File Upload to Server using Retrofit in Android App

We'll design this type of sample Android App using Retrofit Android Library:

Create instance of Retrofit class (You can check basic Retrofit implementation from here)

public class RetrofitApiClient {

    private static final String BASE_URL = "http://yourdomainname.com"; //I used IP of my local machine

    private static Retrofit retrofit = null;

    private static Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    private RetrofitApiClient() {} // So that nobody can create an object with constructor

    public static synchronized Retrofit getClient() {
        if (retrofit==null) {

            int timeOut = 5 * 60;
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(timeOut, TimeUnit.SECONDS)
                    .writeTimeout(timeOut, TimeUnit.SECONDS)
                    .readTimeout(timeOut, TimeUnit.SECONDS)
                    .build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(client)
                    .build();
        }
        return retrofit;
    }
}

The Interface class is given below:

public interface ApiInterface {

    @Multipart
    @POST("file_upload_api/upload.php")
    Call<ResponseModel> fileUpload(
            @Part("sender_information") RequestBody description,
            @Part MultipartBody.Part file);
}

File upload method is here:

public static void fileUpload(String filePath, ImageSenderInfo imageSenderInfo) {

    ApiInterface apiInterface = RetrofitApiClient.getClient().create(ApiInterface.class);
    Logger.addLogAdapter(new AndroidLogAdapter());

    File file = new File(filePath);
    //create RequestBody instance from file
    RequestBody requestFile = RequestBody.create(MediaType.parse("image"), file);

    // MultipartBody.Part is used to send also the actual file name
    MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

    Gson gson = new Gson();
    String patientData = gson.toJson(imageSenderInfo);

    RequestBody description = RequestBody.create(okhttp3.MultipartBody.FORM, patientData);

    // finally, execute the request
    Call<ResponseModel> call = apiInterface.fileUpload(description, body);
    call.enqueue(new Callback<ResponseModel>() {
        @Override
        public void onResponse(@NonNull Call<ResponseModel> call, @NonNull Response<ResponseModel> response) {
            Logger.d("Response: " + response);

            ResponseModel responseModel = response.body();

            if(responseModel != null){
                EventBus.getDefault().post(new EventModel("response", responseModel.getMessage()));
                Logger.d("Response code " + response.code() +
                        " Response Message: " + responseModel.getMessage());
            } else
                EventBus.getDefault().post(new EventModel("response", "ResponseModel is NULL"));
        }

        @Override
        public void onFailure(@NonNull Call<ResponseModel> call, @NonNull Throwable t) {
            Logger.d("Exception: " + t);
            EventBus.getDefault().post(new EventModel("response", t.getMessage()));
        }
    });
}

Here I used EventBus Library to notify my UI from a different class. The simple implementation of EventBus is given here.

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:

<?php
    $target_dir = "files/"; //folder name where your files will be stored. create this folder inside "file_upload_api" folder
    $target_file = $target_dir . basename($_FILES["file"]["name"]);

    $response = array('success' => false, 'message' => 'Sorry, there was an error uploading your file.');

    $data = $_POST['sender_information'];
    $json_data = json_decode($data , true);
    $sender_name = $json_data['sender_name'];
    $sender_age = $json_data['sender_age'];


    if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
        $response = array('success' => true, 'message' => 'Hello '.$sender_name.'! You are '.$sender_age.' years old. Your image is uploaded successfully!');

    echo json_encode($response);
?>

Disclaimer

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.