DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Building a RESTful Service Using ASP.NET Core and dotConnect for PostgreSQL
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • Breaking Up a Monolithic Database with Kong

Trending

  • Liquid Glass, Material 3, and a Lot of Plumbing
  • AI-Driven RAG Systems: Practical Implementation With LangChain
  • The Middleware Gap in AI Agent Frameworks
  • Alternative Structured Concurrency
  1. DZone
  2. Coding
  3. Frameworks
  4. How to Upload Images to an ASP.NET Core REST Service With Xamarin.Forms

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.

By 
Michele Ferracin user avatar
Michele Ferracin
·
Feb. 19, 18 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
102.9K Views

Join the DZone community and get the full member experience.

Join For Free

With 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.

  1. We select .NET Core -> ASP.NET Core Web Application, give a name and hit OK.
  2. 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)

ASP.NET REST Web Protocols ASP.NET Core Web Service Upload xamarin.forms

Published at DZone with permission of Michele Ferracin. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Building a RESTful Service Using ASP.NET Core and dotConnect for PostgreSQL
  • Spring Boot - How To Use Native SQL Queries | Restful Web Services
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • Breaking Up a Monolithic Database with Kong

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook