Trying to post files with Ionic 2 to ASP.NET Web Api


#1

Hello! I’m trying to post an image with another parameters to an ASP.NET Web Api.
I have the following method in an Ionic 2 service:

addLog (title, message, enablePosition, lat, lng, date, img) {    
let url = this.apiurl + '/logs';
    let ft = new Transfer();
    let uploadOptions = {
            fileKey: 'img',
            fileName: "image001",
            mimeType: 'image/jpeg',
            httpMethod: 'POST',
            chunkedMode: false,
            params: {
                 title: title,
                 message: message,
                 date: date,
                 positionEnabled: enablePosition,
                 lat:lat,
                 lng:lng
             }
        }; 
        ft.onProgress(this.onProgress);
        ft.upload(img, url, uploadOptions, false)
        .then((result: any) => {
          console.log("success");
        }).catch((error: any) => {
          console.log(error);
        });
}

This code returns an error 404 from the server. But, if I use the uri encoded url:

The service is called here:

submit(){
    var lat = '0';
    var lng = '0';
    if(this.sendLocation){
      Geolocation.getCurrentPosition().then((position) => {
        lat = position.coords.latitude.toString().replace('.',',');
        lng = position.coords.longitude.toString().replace('.',',');
        this.logsService.addLog(this.title, this.message, this.sendLocation, lat, lng, new Date().toLocaleString(), this.base64Image);
        this.showAlert();
      });
    } else {
    this.logsService.addLog(this.title,  this.message, this.sendLocation, lat, lng, new Date().toLocaleString(), this.base64Image);
        this.showAlert();
}
  }

let body = 'title=' + encodeURIComponent(title) + '&message=' + encodeURIComponent(message) + '&positionEnabled=' + encodeURIComponent(enablePosition) + '&date=' + encodeURIComponent(date) + '&lat=' + encodeURIComponent(lat) + '&lng='+ encodeURIComponent(lng)

, the post is made. The problem is that the image file is not being posted in the ASP.NET Rest server.

At the other hand, in my web api I have the following post method:

public void Post(string title, string message, string date, bool positionEnabled, string lat, string lng)
    {
        HttpRequestMessage request = this.Request;
        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
        var provider = new MultipartFormDataStreamProvider(root);

        var repo = new LogsRepository();
        repo.Add(new MessageLog(title, message, positionEnabled, double.Parse(lat), double.Parse(lng), DateTime.Parse(date)));
    }

It’s always getting inside the if condition.
I’m getting mad with this, I don’t figure out how to post files. Please help!
And sorry for my english, it’s not my first language.