Uploading Images to Web API from Android Device

... by Semir in DevelopmentFebruary 26, 2019 18

This blog explains how to upload an image from an Android devices to Asp.Net Web API endpoints. It also explains the necessary configurations that are required to to accept Web API requests to IIS Express from and Android Simulator or device.


Android App

In the ReseClient.java file of the android application:

\app\src\main\java\com\instinctcoder\uploadfiles\rest\RestClient.java

The web service URL is specified, in this case I have used the following IP address which is also the IP address assigned to my laptop by DHCP protocol by wireless router.

private String URL ="http://192.168.1.49:58938/api/";

I have also used port 58938 to communicate to my backend web service.

The above two information (i.e. IP address and port number) are very vital for the Android App to be able to communicate to the backend web service.

As you might already know the IP address for a given host could be found by the typing the following command in the command line.

Asp.net MVC Web Service

Step-1: Specify the location for the uploaded images from Android devices

In the Asp.net Webs Service, locate the file within the project by the name FileUploadController.cs

\UploadFile-Asp.net\Controllers\FileUploadController.cs

In the post controller I have used the following directory to place all the posted image from the Android app.

var uploadPath = HttpContext.Current.Server.MapPath("~/Uploads");

However, I believe you should be able to specify any folder location for the posted images, as far as the Asp.net application have privilege to access the folder.

Step-2: Change IIS Express Settings

If you would like to debug the Web API on IIS Express during development, you need to configure applicationhost.config file ocated within

\UploadFile-Asp.net\.vs\config\applicationhost.config

To bind any incoming request to 192.168.1.49:58938 ip address and port number, to bind to the Post action within FileUpload controller in the asp.net webservice.

Step-3: Configure Windows Firewall

Now, all that in place there is one final step that I need to follow in order to allow the request to be also possible from external different address (i.e. from actual Android phone, rather than the Android Emulator)

  • The command below is to add the IP address and the port number of the web service to the http.sys file.

    netsh http add urlacl url=http://192.168.1.33:58938/ user=everyone

  • The second command is to allow firewall to register the port number to its trusted source, and the command is a show below:

    netsh advfirewall firewall add rule name="IISExpressWeb" dir=in protocol=tcp localport=58938 profile=private remoteip=localsubnet action=allow

Summary

Asp.Net MVC Web API provides flexibility for communicating with Android Apps either through RESTful API or binary data like uploading media files to the Web Server.



Leave a comment

SemirIbrahim