Service Now Upload Image to Table Api

With this blog postal service, 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 unabridged solution of this example here.

Server-Side (ASP.Net Core)

To create a Balance service, we create an ASP.Net Core Spider web Application project.

  1. We select .Net Core -> ASP.Internet Core Web Application, requite a name and striking OK.
  2. We choose:

Our Project volition look like this:

Now we add a Controller in the Controllers folder to handle our moving-picture show upload. Right-click in the Controllers folder, Add -> Controller, we choose empty controller and nosotros requite the name ImageController.cs.

Now we write this code in the ImageController grade:

          using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using Organization.IO; using System.Threading.Tasks;  namespace IC6.Xamarin.WebApi.Controllers {     [Produces("application/json")]     [Road("api/Image")]     public class ImageController : Controller     {         private readonly IHostingEnvironment _environment;          public ImageController(IHostingEnvironment surroundings)         {             _environment = environment ?? throw new ArgumentNullException(nameof(environment));         }          // Mail service: api/Epitome         [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))                 {                     expect file.CopyToAsync(fileStream);                 }             }         }     } }        

The upload of the paradigm 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, nosotros create a new interface called IApiService that representes the capabilites of our web service. We create too a form 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 Arrangement.IO; using Organization.Cyberspace.Http; using System.Threading.Tasks;  namespace IC6.Xamarin.PictureUpload {     internal class ApiService : IApiService     {         private string url = "http://xxxxxxxxx/api/image/";          public async Job UploadImageAsync(Stream prototype, 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 Organization.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");             using (var customer = new HttpClient())             using (var formData = new MultipartFormDataContent())             {                 formData.Add(fileStreamContent);                 var response = look client.PostAsync(url, formData);                 render response.IsSuccessStatusCode;             }         }     } }        

The UploadImageAsync method makes the push request with a HttpClient. Nosotros configure our HttpClient to represent a spider web form with an fastened file. Nosotros exercise this by correctly setting up the Headers of the HttpContent and creating a MultiPartFormDataContent equally the content of the request. The ContentDisposition is very important and we demand to specify that the "Name" of the form-data is called "file" to get a lucifer in the MVC model binding.

The Image Picker

Nosotros demand to fire upward 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 apply the technique of abstracting the concept with an interface and then provide a specific implementation for each project then our view-model is platform-agnostic.

          using Organization.Threading.Tasks;  namespace IC6.Xamarin.PictureUpload {     public interface IImagePicker     {         Task GetImageStreamAsync();     } }        

(The source code for the UWP and Android implementation is directly on GitHub).

At present, in our view-model where we'll handle the picking and the uploading of the image, we tin can write something similar this:

                      public Control UploadImage         {             get             {                 if (_uploadImage == aught)                 {                     _uploadImage = new Command(                         async () =>                         {                             attempt                             {                                 var theFileToUpload = expect _imagePickerSvc.GetImageStreamAsync();                                  UploadStatus =  expect _apiSvc.UploadImageAsync(theFileToUpload.StreamSource, theFileToUpload.FileName);                             }                             catch (Exception ex)                             {                                 System.Diagnostics.Debug.WriteLine(ex.Bulletin);                             }                         },                         () =>                         {                             return true;                         });                 }                  render _uploadImage;             }         }        

Tips & Tricks

To debug the app and the service at the same time we tin can right click a project -> Debug- > Commencement a new instance.

If nosotros debug with IIS Express and we want to access the web service from a real or emulated device we demand to edit applicationhost.config file and showtime Visual Studio as administrator.

TL;DR

In this blog post, we've created a RESTful web-service with ASP.Internet core to handle the upload of an image. This can be used to handle a file of any kind, as well. We also implemented the client side to telephone call the API and to provide the user with an interface to choose the epitome with a file picker.

References

PictureUpload on GitHub (https://github.com/phenixita/IC6.Xamarin.PictureUpload)

Topics:

mobile, mobile app development, xamarin.forms, asp.net cadre

rileynotholow.blogspot.com

Source: https://dzone.com/articles/how-to-upload-images-to-an-aspnet-core-rest-servic

0 Response to "Service Now Upload Image to Table Api"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel