How to Upload Images to an ASP.NET Core REST Service With Xamarin.Forms
Learn how to upload a picture to a RESTful service developed with ASP.NET Core using Xamarin.Forms in this mobile web app tutorial.
Join the DZone community and get the full member experience.
Join For FreeWith this blog post, we continue the exploration of Xamarin.Forms. We'll see how to upload a picture to a RESTful service developed with ASP.NET Core.
You can download the entire solution of this example here.
Server-Side (ASP.Net Core)
To create a REST service, we create an ASP.NET Core Web Application project.
- We select .NET Core -> ASP.NET Core Web Application, give a name and hit OK.
- We choose:
Our Project will look like this:
Now we add a Controller in the Controllers folder to handle our picture upload. Right-click in the Controllers folder, Add -> Controller, we choose empty controller and we give the name ImageController.cs.
Now we write this code in the ImageController class:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading.Tasks;
namespace IC6.Xamarin.WebApi.Controllers
{
[Produces("application/json")]
[Route("api/Image")]
public class ImageController : Controller
{
private readonly IHostingEnvironment _environment;
public ImageController(IHostingEnvironment environment)
{
_environment = environment ?? throw new ArgumentNullException(nameof(environment));
}
// POST: api/Image
[HttpPost]
public async Task Post(IFormFile file)
{
var uploads = Path.Combine(_environment.WebRootPath, "uploads");
if (file.Length > 0)
{
using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
}
}
}
}
The upload of the image is implemented in the Post method. The IFormFile file parameter represents the uploaded file. This variable is assisgned automatically by ASP.NET if the model binding finds a correct match in the request from the client.
Client-Side (App)
API Calls
In our shared Project of the Xamarin.Forms app, we create a new interface called IApiService that representes the capabilites of our web service. We create also a class that implements that interface and we call it ApiService.
using System.IO;
using System.Threading.Tasks;
namespace IC6.Xamarin.PictureUpload
{
public interface IApiService
{
Task UploadImageAsync(Stream image, string fileName);
}
}
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace IC6.Xamarin.PictureUpload
{
internal class ApiService : IApiService
{
private string url = "http://xxxxxxxxx/api/image/";
public async Task UploadImageAsync(Stream image, string fileName)
{
HttpContent fileStreamContent = new StreamContent(image);
fileStreamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "file", FileName = fileName };
fileStreamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
using (var client = new HttpClient())
using (var formData = new MultipartFormDataContent())
{
formData.Add(fileStreamContent);
var response = await client.PostAsync(url, formData);
return response.IsSuccessStatusCode;
}
}
}
}
The UploadImageAsync method makes the push request with a HttpClient. We configure our HttpClient to represent a web form with an attached file. We do this by correctly setting up the Headers of the HttpContent and creating a MultiPartFormDataContent as the content of the request. The ContentDisposition is very important and we need to specify that the "Name" of the form-data is called "file" to get a match in the MVC model binding.
The Image Picker
We need to fire up an image picker to allow the user to select the image he/she wants to send.
The code for this feature is platform-specific and use the technique of abstracting the concept with an interface and then provide a specific implementation for each project so our view-model is platform-agnostic.
using System.Threading.Tasks;
namespace IC6.Xamarin.PictureUpload
{
public interface IImagePicker
{
Task GetImageStreamAsync();
}
}
(The source code for the UWP and Android implementation is directly on GitHub).
Now, in our view-model where we'll handle the picking and the uploading of the image, we can write something like this:
public Command UploadImage
{
get
{
if (_uploadImage == null)
{
_uploadImage = new Command(
async () =>
{
try
{
var theFileToUpload = await _imagePickerSvc.GetImageStreamAsync();
UploadStatus = await _apiSvc.UploadImageAsync(theFileToUpload.StreamSource, theFileToUpload.FileName);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
},
() =>
{
return true;
});
}
return _uploadImage;
}
}
Tips & Tricks
To debug the app and the service at the same time we can right click a project -> Debug- > Start a new instance.
If we debug with IIS Express and we want to access the web service from a real or emulated device we need to edit applicationhost.config file and start Visual Studio as administrator.
TL;DR
In this blog post, we've created a RESTful web-service with ASP.Net core to handle the upload of an image. This can be used to handle a file of any kind, too. We also implemented the client side to call the API and to provide the user with an interface to choose the image with a file picker.
References
PictureUpload on GitHub (https://github.com/phenixita/IC6.Xamarin.PictureUpload)
Published at DZone with permission of Michele Ferracin, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments