Uploading image in Ionic application with ASP.Net Web API


n
n
nMany .Net developers have struggled so much to upload image from an Ionic application with ASP.Net Web API.
n
nIn this tutorial, I will show you how easy it is to upload image in an ionic application via .Net Web API.
n
nSince this tutorial is not for beginner I will skip how to create a new ionic app via ionic CLI.
n
n

nASP.Net Web API Controller

nBelow is the web api controller that will handle the image upload:
n
n
n

[HttpPost]n        [Route("upload")]n        public HttpResponseMessage uploadImage()n        {n            var request = HttpContext.Current.Request;nn            if (Request.Content.IsMimeMultipartContent())n            {n                if (request.Files.Count > 0)n                {n                    var postedFile = request.Files.Get("file");n                    var title = request.Params["title"];n                    string root = HttpContext.Current.Server.MapPath("~/Images");n                    root = root + "/" + postedFile.FileName;n                    postedFile.SaveAs(root);n                    //Save post to DBn                        return Request.CreateResponse(HttpStatusCode.Found, newn                        {n                            error = false,n                            status = "created",n                            path = rootn                        });n                    n                }n            }n            n            return null;n        }nn

n
n
nThe above code is self explanatory, however I want you to take note of these two lines:
n
n

  var postedFile = request.Files.Get("file");n  var title = request.Params["title"];

n
nI will be making reference to those two line in the ionic app code.
n
n

nSetting up the ionic project

nCreate a blank ionic app and install the following cordova and ionic-native plugins:
n
n

ionic cordova plugin add cordova-plugin-filennpm install --save @ionic-native/filenionic cordova plugin add cordova-plugin-camerannpm install --save @ionic-native/cameranionic cordova plugin add cordova-plugin-file-transfernnpm install --save @ionic-native/file-transfern

n
n
nOpen up the app.module.ts file  – ‘src/app/app.module.ts’ and all needed imports and also include them in the providers section of the NgModule.
n
n

import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';nimport { File } from '@ionic-native/file';nimport { Camera } from '@ionic-native/camera';nn  providers: [n    StatusBar,n    SplashScreen,n    {provide: ErrorHandler, useClass: IonicErrorHandler},n    FileTransfer,n    FileTransferObject,n    File,n    Cameran  ]n

n
n
nModify the home.html page to look like so:
n
n

n  n    n  nn  n    n      
nn
nn uploaded Imagen n
n
n n
n

n
nThat just create a form that has a title field and image field. I am also using Ng-If-Else to control which component to show when an image has been selected or not. Fairly simple.
n
nAdd the simple css to home.scss file to make the screen look good
n
n
n

     ion-card{n          margin: 3px !important;n          width: calc(100% - 6px) !important;n          .uploadWrap{n              ion-icon{n                  color:#777;n                  font-size: 150px;n                  text-align: center !important;n                  display: block;n              }n          }n          button{n              height: 40px !important;n          }n      }n

n
n
n
nLet’s move to the home.ts file where we will be doing the major work. Add the required imports
n
n

import { FileTransfer, FileTransferObject, FileUploadOptions } from '@ionic-native/file-transfer';nimport { Camera, CameraOptions } from '@ionic-native/camera';n

n
nDeclare variables  needed:
n
n

imageURI: any;nimageTitle: any;nisImageSelected:boolean = false;n

n
n
nIn this app we will just be getting image from gallery. Add the following code that allow us choose image from the device gallery:
n
n

  chooseFile() {n    let options: CameraOptions = {n      quality: 100,n      destinationType: this.camera.DestinationType.FILE_URI,n      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,n      allowEdit: true,n      encodingType: this.camera.EncodingType.JPEG,n      targetWidth: 500,n      targetHeight: 500,n      saveToPhotoAlbum: falsen    };nnn    this.camera.getPicture(options).then((img) => {n      this.imageURI = img;n      this.isImageSelected =true;n    }).catch((reason) => {n      console.log(reason);n    });n  }n

n
n
nThe full home.ts file should now look like this
n

import { Component } from '@angular/core';nimport { IonicPage, NavController, NavParams, LoadingController } from 'ionic-angular';nimport { FileTransfer, FileTransferObject, FileUploadOptions } from '@ionic-native/file-transfer';nimport { Camera, CameraOptions } from '@ionic-native/camera';nnn@IonicPage()n@Component({n  selector: 'page-home',n  templateUrl: 'home.html',n})nexport class HomePage {nnn  imageURI: any;n  imageTitle: any;n  isImageSelected:boolean = false;nn  constructor(public navCtrl: NavController, public navParams: NavParams,n    private transfer: FileTransfer,n    private camera: Camera,n    public loadingCtrl: LoadingController) {n  }nnn  chooseFile() {n    let options: CameraOptions = {n      quality: 100,n      destinationType: this.camera.DestinationType.FILE_URI,n      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,n      allowEdit: true,n      encodingType: this.camera.EncodingType.JPEG,n      targetWidth: 500,n      targetHeight: 500,n      saveToPhotoAlbum: falsen    };nnn    this.camera.getPicture(options).then((img) => {n      this.imageURI = img;n      this.isImageSelected =true;n    }).catch((reason) => {n      console.log(reason);n    });n  }nn  doImageUpload() {n    let loader = this.loadingCtrl.create({n      content: "Uploading..."n    });n    loader.present();n    let filename = this.imageURI.split('/').pop();n    const fileTransfer: FileTransferObject = this.transfer.create();nn    let options: FileUploadOptions = {n      fileKey: "file",n      fileName: filename,n      chunkedMode: false,n      mimeType: "image/jpg",n      params: { 'title': this.imageTitle }n    };nn    fileTransfer.upload(this.imageURI, "http://localhost/api/upload",options).then((res)=>{nnn    },(err)=>{nn    });nn  } nn}n

n


nIn the doImageUpload function above there two things that are important to these two lines I talked about in the web api controller
n
n
n

  var postedFile = request.Files.Get("file");n  var title = request.Params["title"];

n

n

n
nfileKey: “file”
nparams: { ‘title’: this.imageTitle }
n
nThe file and the title in the params object. You can add more parameters to the params object and get the value with they key in the api.
n
nHappy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top