Android Studio Upload Any Files to ASP.Net Web API




In this tutorial, we like to show you how to upload files to ASP.Net Web API.

Todo
We need some kind of apps that will take photo for us and upload to server, in case user forgotten what been uploaded to server we provide another button upload all photos captured and upload as zip file to server. This tutorial will use this ASP.NET Web API code as our server to helps us receive uploading files.

Tool used
1. Android Studio 1.5.1
2. Retrofit 1.6.1
3. Picasso 2.5.2

Before you read below code, just want to make you feel comfortable with below code is working, please watch this video 😉
View Demo – Android Studio Upload Any Files to ASP.Net Web API

Android Studio Upload Any Files to ASP.Net Web API

Code
1. Let’s start create project, UploadFiles. The setting of the project are show as below images which is quite straight forward.

2. Then, create all the necessary package as below image, and we will explain in later step.
Android Studio Upload Any Files to ASP.Net Web API

3. As i mentioned before, i’m a big fan of Retrofit, so in this post again retrofit helps us again in solving our puzzle and It’s helps most of my daily work (Thank you 🙂 ). Retrofit provide us the functionality for us to upload file which mean save us again from headache. Beside, we also use Picasso for helping us to load image into ImageView. So please navigate to app > build.gradle and copy the following contents

4. As we need save photo in phone’s SDCard and also uploading files to server, we need to grant these permission for this app, please navigate to app > src > main > AndroidManifest.xml and add the highlighted lines.

5. Add 3 buttons and ImageView into app>src>main>res>layout>activity_main.xml, code will look like below

6. helper package is where we put common function which we could share code across all packages.

Then, please navigate to app>src>main>java>com.instinctcoder.uploadfiles > helper. and create a class , FileHelper.java FileHelper is the file that we created to do some function related to file.

7. service package is the package that contains REST Service interface files that will be used with Retrofit to communicate with ASP.NET Web API.

Please navigate to com.instinctcoder.uploadfiles > rest > service and create a Interface , UploadService.java and copy the following code

We will show you 2 different ways to upload files to server, synchronous and asynchronous. UploadSync is the synchronous method is the method that need to wait for server response before able to execute the rest of the code. and this function has 1 parameter TypedFile which will be the content of the file. On other hand, Upload is asynchronous method that allow us to use callback meaning we doesn’t need to wait server response. We will show more detail in later step.

8. rest package is the package include files that use to perform internet connection activity. Please navigate com.instinctcoder.uploadfiles > rest and create class and named it CancelableCallback.java. Copy the following code.

As for Retrofit 1, there is no easy way for us to cancel on going request and the below code is only workaround which getting code from here , it’s basically just ignore the response.

9. In the same package, create RestClient.java. This is the main file that help us to communicate with server. This file is quite self-explanatory, feel free to comment if you need more clarification.

9. In the same package, create UploadSync.java class. The purpose of this file is to show you how to call the synchronous method in AsyncTask, and this will help us to inform user there is a long waiting process running at the back.

10. At last, please navigate to com.instinctcoder.uploadfiles > ui, update the MainActivity.java file as follow.

11. That’s all, it you feel this tutorial not confuse you and want to get any future post, please follow us on facebook, google+, and tweeter. 😛




JOIN OUR NEWSLETTER
In case you want to get any future post please allowed us deliver new posts direct into your inbox Or follow us on facebook, google+, tweeter
We hate spam. Your email address will not be sold or shared with anyone else.
  • Victor

    Hi Tan,
    Im testing your code. And always give me the 404 error.
    Then I installed fiddler on my laptop to see what URL i was calling and found the error.
    For fiddler to work I needed to configura the network in the Android Emulator.
    Then the application worked and uploaded the image to the server.
    But when I turned the configuration of fiddler in Android Emulator it went back to the 404 error.
    Do you have any ideia why?

    • Tan Woon How

      Oh really? Could you share the config ? I never configure that. As i used retrofit and that allowed us to debug direct into .Net code

      For 404 error I not sure why.

      • Victor

        Hi Tan,
        Thanks for your anwser.
        But I found the error, it was here requestFacade.addHeader(“Host”, “localhost”);
        I changed the localhost to the host name server and it worked.
        Can you explain me I do i need to put this header?
        Thx

        • Tan Woon How

          Hi,
          It should not be necessary, we add this line is because we use it for debugging purposes. Please remove the above line from you code and try again.

  • miguel

    hello!, great tutorial.

    i need some guide to solve in the c# code. When choose the file and upload this i receive the exception:

    Message:
    Processing
    of the HTTP request resulted in an exception. Please see the HTTP response
    returned by the ‘Response’ property of this exception for details.

    Response:
    {StatusCode:
    415, ReasonPhrase: ‘Unsupported Media Type’, Version: 1.1, Content:
    , headers:{}}

  • Marium Hashmi

    on capturing picture it says “couldn’t save the image”
    how to solve that?

    • Tan Woon How

      What is the error? Is from server or the device?

  • iS_Tom

    can see how the server receives the data from the client android?

    • Tan Woon How

      You mean video ? https://youtu.be/FoC1HxwLxXw

      Or server code? Below link is the webapi that receive data. http://instinctcoder.com/angularjs-upload-multiple-files-to-asp-net-web-api/

      • iS_Tom

        Please help me. How to connect your phone to the local server? phone and a PC connected to the same router.

        • Tan Woon How

          You need to configure the router, ask your network admin to do it for you. In case you use “TP LINK” router and If you could access the router control panel, then look for “Forwarding” , just like the image below https://uploads.disquscdn.com/images/b19b8fe5d7d833aff287f8c971a10683c6c820c819de7f9e125cc9d757bd22b2.png

          and also make sure your machine firewall configure to allow inbound and outbound for the port you like to configure. In case you use Window, please navigate to –> Control PanelSystem and SecurityWindows Firewall and add inbound and outbound, something like this image, If you found this is too troublesome you could temporary turn off the firewall and try out but remember turn it back. :). Hopes that help!
          https://uploads.disquscdn.com/images/bf71d81a7ca24c643f6f5973402aac6668bc376c1b4cbae95ada4263a8356c9b.png

          • iS_Tom

            Thank you. Faced with another problem. When I send a photo to the server, there is error 501 not implemented. It is possible that a server is not available.

          • iS_Tom

            With the help of an emulator image is sent. But if you send from your phone, then there is an error 403. Can you help?

          • Tan Woon How

            What is the URL you set in your code?

          • iS_Tom

            Address written ip computer on the local network 192.168.0.104, port 7899, a port is registered in the server. In the folder where the server is not removed attribute “read only”.

          • Tan Woon How

            Firstly, this ip is your laptop? When you use emulator to upload? If you dont mind try grant everyone a t the folder and try out .

          • iS_Tom
          • Tan Woon How

            Hmmm…I really want to help but this error could be many reason… Have you grant the folder permission? Or if you don’t mind me to get access into your environment may be to have just a look? I’m not sure i can help. Yes, then send your team viewer id to my admin[a]instinctcoder[dot]com 😉

          • iS_Tom

            Access to the folder where the server is available. As I understand it, you hotie connect to my PC in order to help solve the shed?

          • Tan Woon How

            I guess yes to your answer . I just go into your pc and see am i able to help you or not .

          • iS_Tom

            Hello, can you suggest how one request to send the variable “Login” along with a picture. And how to change the server FileUploadController for “login” with the picture.

          • iS_Tom

            Hey. I use both in your example library retrofit. Please tell me how to increase the wait time. With a slow Internet often time out error.