Retrofit Upload File Tutorial – Uploading and Downloading Images

Struggling to upload images to your server? Here is the Retrofit Upload File Tutorial. The retrofit library also gives an option to send the Multipart HTTP requests, and we can use it for uploading files. So let’s learn how we do this in our Android project. Here I am going to use PHP and MySQL on the server side.

Check out the Update File Upload Tutorial that Supports Android 10 Here

Building APIs

We will send the file to our server from the android application. So at the server side, we need to catch the file, and then we need to store it on the server. To do all these tasks, we create API. So let’s start. Here I am using XAMPP server; you can use any other server as well.

Creating MySQL Database

  • The first step is creating the database. And we need a database shown as below.
retrofit upload file tutorial database
Database
  • You can use the following SQL for creating the above database.

Creating PHP Project

  • For PHP Project I am using PHP Storm. But you can use notepad++, sublime or any other IDE as well.
  • Create a new project inside htdocs (c:/xampp/htdocs). I have created a project named ImageUploadApi.

Defining Constants

  • First we will create a file named Constants.php to define all the required constants.

Connecting to Database

  • Now we will connect to our database. For this create a php class named DbConnect.php and write the following code.

The Uploads Directory

  • Create a directory inside your project named uploads. In this folder we will store all the images uploaded by the user.

retrofit file upload uploads directory

Handling File Upload and Download

  • Now we will create one more class named FileHandler.php to save and retrieve the images.

Handling API Calls

  • Lastly we need to handle the calls of our Android App. So for this we will create a php file named Api.php and in this file we will handle all the api calls.

  • Now lets test our API and for this we can use any REST Client. I am using POSTMAN.
retrofit file upload api
Testing API
  • So our API is working fine. Now lets move into the Android Part.

Retrofit Upload File Tutorial

  • Here begins the main part. The first step always is creating a new Android Studio Project.

Creating a new Project

  • I have created a project named RetrofitFileUpload.
  • Now once the project is completely loaded we will add the Retrofit and Gson to it.

Adding Libraries

  • Come inside app level build.gradle file and add the following given lines to it inside the dependencies block.

  • Now sync your project.

Creating the Model Class for Response

  • The response we are getting from the server is.

  • So to parse it we will create a model class. So create a class named MyResponse.java and write the following code.

Creating API Interface

  • Now we need an interface to define all the API calls. So create an interface named Api.java and write the following code.

Uploading the File

Creating Interface

  • To upload a file we need a file, and to get the file we will create a file chooser. So we will create a button and by tapping this button we will open a file chooser activity.
  • So first create a button inside activity_main.xml.

Checking the Read Storage Permission

  • So if the android is running the version greater than Lollipop, then we need to ask for the permission on runtime. But we also need to define the permission in the manifest file. The permission here is the Read Storage Permission as to upload a file; first we need to read the file from the storage, and without storage permission, we cannot do it.
  • So first open AndroidManifest.xml and define the read permission.

  • We also defined the internet permission as this is also needed. But we don’t need to ask internet permission on runtime.  So on onCreate() we will add the following code.

  • The above code will stop the application and open the settings page, if the app is not having the read storage permission.

Choosing a File

  • We will add the following code on Button Click Event to open the file chooser.

  • Now we also need to track the result of this file chooser intent. And to do this we need to override the method onActivityResult().

  • We got the image Uri but it is not enough we need to actual image path. For this we will create one more method.

Getting Absolute Path from Uri

  • For getting the absolute path we can use the following method.

Uploading the File

  • Now to upload the file we will create the following method.

  • Now we just need to club everything inside our MainActivity.java.

  • Now try running your application you will see something like this.
retrofit upload file tutorial
Retrofit Upload File Tutorial
  • You can see it is working absolutely fine.

Downloading Images Back

  • We have already created an API call to fetch the images.

retrofit file upload tutorial

Retrofit Upload File Source Code

  • In case you are having any troubles you can get my source code from here. The source code contains all the PHP scripts and the android project.

Retrofit Upload File Source Code Download

So that’s all for this Retrofit Upload File Tutorial guys. If you have any questions, then please leave your comments. And if you found this post helpful, then please SHARE it. Thank You 🙂

21 thoughts on “Retrofit Upload File Tutorial – Uploading and Downloading Images”

  1. Sir,

    This project is throwing Exception “Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $”.
    Please see to it.

    Reply
  2. Please how do i add multiple fields to the database table instead of only three, i tried adding more fields to your api but can’t get any progress. any help will be appreciated.
    lets say
    id
    url
    description
    event_date
    event_video

    Reply
    • Try this code to create function:
      function createEvent($event_video, $description, $event_date, $file, $extension)
      {
      $name = round(microtime(true) * 1000) . ‘.’ . $extension;
      $filedest = dirname(__FILE__) . UPLOAD_PATH . $name;
      move_uploaded_file($file, $filedest);

      $url = $server_ip = gethostbyname(gethostname());

      $stmt = $this->con->prepare(“INSERT INTO event ((event_video, description, event_date, url) VALUES (?, ?, ?, ?)”);
      $stmt->bind_param(“ssss”, $event_video, $description, $event_date, $name);
      if ($stmt->execute())
      return true;
      return false;
      }

      Reply
  3. Thanks but update your tutorial in android o when you want to use uri of image then you have to use file provider.above code crash on android Oreo.once you check it

    Reply
  4. on Button Click application Crash Application Actually “getRealPathFromURI”function create exception

    //this part call on Image View Onclick
    private void selectImage() {
    Intent intent=new Intent();
    intent.setType(“image/*”);
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent,ImageResponse);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode==ImageResponse && resultCode==RESULT_OK && data!=null)
    {
    path=data.getData();

    try {
    bitmap= MediaStore.Images.Media.getBitmap(getContentResolver(),path);
    imageView.setImageBitmap(bitmap);
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

    //This function call on send button
    public void Register(View view) {
    //String Image=ImagetoString();
    File file = new File(getRealPathFromURI(path));
    String name=firstname.getText().toString(),lname=lastname.getText().toString(),
    password1=password.getText().toString(),email1=email.getText().toString(),otherField1=””;
    RequestBody name1 = RequestBody.create(MediaType.parse(“text/plain”), name);
    RequestBody lastname1 = RequestBody.create(MediaType.parse(“text/plain”), lname);
    RequestBody password2 = RequestBody.create(MediaType.parse(“text/plain”), password1);
    RequestBody email2 = RequestBody.create(MediaType.parse(“text/plain”), email1);
    RequestBody otherField = RequestBody.create(MediaType.parse(“text/plain”), otherField1);
    RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(path)),file);
    Call call=RetrofitClient.getInstance().getApi().uploadImage(name1,lastname1,password2,
    email2,otherField,otherField,otherField,otherField,otherField,otherField,requestFile,otherField,otherField,otherField,otherField,otherField,otherField,otherField,otherField);
    call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {

    try
    {
    String s=response.body().string();
    Toast.makeText(MainActivity.this,s+”valid Api”, Toast.LENGTH_SHORT).show();
    startActivity(new Intent(MainActivity.this,MainActivity.class));
    }
    catch (IOException e)
    {
    e.printStackTrace();
    }

    }

    @Override
    public void onFailure(Call call, Throwable t) {
    Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
    }
    });

    }

    Reply
  5. can we upload multiple image using this RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
    methods

    Reply
  6. Call uploadImage(@Part(“image\”; filename=\”myfile.jpg\” “) RequestBody file, @Part(“desc”) RequestBody desc);

    @Part(“image\”; filename=\”myfile.jpg\” “) RequestBody file, please explain this part

    Reply
  7. Fatal error: Call to a member function bind_params() on boolean in C:\wamp64\www\ImageUploadApi\FileHandler.php on line 26

    $stmt->bind_param(“ss”, $desc, $name);

    Reply

Leave a Comment