0

I am working on my mobile application using Angularjs and c# Web API. I am new to this platform. In my application there is a part in which I have to upload files and data from client (Angularjs) to server (c#). While posting data, the FormData posted successfully from the client side but received as empty data in the server side.I have been trying to figure it out since the last month but still unable to get a solution. Please help me out. This is my code:

    if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

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


        try
        {

            await Request.Content.ReadAsMultipartAsync(provider);   

            var Token = provider.FormData.GetValues("Token")[0];
            var Product = provider.FormData.GetValues("Product")[0];
            var Reference = provider.FormData.GetValues("Reference")[0];
            var ModuleId = Convert.ToInt32(provider.FormData.GetValues("ModuleId")[0]);
            var Repeat = "";
            if (provider.FormData.GetValues("Repeat") == null)
            {
                Repeat = "N";
                // var Repeat = provider.FormData.GetValues("Repeat")[0];
            }
            else
            {
                Repeat = "Y";
            }

            var Description = provider.FormData.GetValues("Description")[0];

            var Attachment1 = provider.FileData[0];

            if (!CRQExtentions.IsValidToken(Token))
                //  return new HttpResponseMessage(HttpStatusCode.Unauthorized);
                return Request.CreateResponse(HttpStatusCode.Unauthorized, "Invalid Token");


            var tr = new TicketRepository();

            var res = tr.AddTicket(Token, Product, Reference, ModuleId, Repeat, Description, Attachment1, Attachment2);


            string s = "Success";
            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            return Request.CreateResponse(HttpStatusCode.OK, new { data = "Test msg" });

        }
        catch (Exception e)
        {
            string f = "Failed";
            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            return Request.CreateResponse(HttpStatusCode.BadRequest, new { data = "Test msg" });
        }

HTML:

    <form enctype="multipart/form-data" ng-submit="uploadDataWithFile()">
    <input type="file" file-model="myFile"  name="Attachment1" multiple />
    <input type="button" ng-click="uploadDataWithFile()" value="Send" name="button" /></form>

ANGULARJS:

myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.post['Accept'] = 'application/json, text/javascript';
$httpProvider.defaults.headers.post['Content-Type'] = 'multipart/form-data; charset=utf-8';}]);

myApp.service('fileUpload', function ($http) {
this.uploadFileToUrl = function (file, uploadUrl) {
    var fd = new FormData();
    fd.append('Attachment1', file);
    //console.log(fd);
    $http.post(uploadUrl, fd, {
        //withCredentials: false,
        headers: {
            'Content-Type': undefined
        },

        transformRequest: angular.identity,
        responseType: "arraybuffer"
    }).success(function (response, status, headers, config) {
        console.log(response);

        if (status == 200 || status == 202) {
            //do whatever in success
        }
        else {
            // handle error in  else if needed 
        }
    }).error(function (error, status, headers, config) {
        console.log(error);
        ons.notification.alert("Error in Saving New CRQ");
        // handle else calls
    });
    }
    });

    myApp.controller('NewCRQController', ['$scope', '$http', 'fileUpload', function ($scope, $http, fileUpload) {
    $scope.uploadDataWithFile = function () {
    var file = $scope.myFile;
    console.dir(file);
    var checkedItem;
    if ($scope.switchon == true) {
        checkedItem = "Y";
    }
    else {
        checkedItem = "N";
    }
    var uploadUrl = "http://localhost:11663/api/Tickets/CreateNewCrqWithFiles";
    fileUpload.uploadFileToUrl(file, uploadUrl);
}
    }]);

Some screenshots of errors

3
  • Assuming you are constructing your form data properly and assuming you are sending only one file at a time (though you have set multiple in file type) set contentType: false and processData: false in the $http.post. Also in web api action, have the method as public YourReturnTypeCreateNewCrqWithFiles(HttpPostedFileBase Attachment1) Commented Aug 22, 2016 at 11:50
  • Thank you @Developer. I tried what you said but it seems I need a form submit in order to submit multipart/form-data. If I use a form submit, I won't be able to get a response message from the server. So I am trying some other way like using a blob. Commented Aug 24, 2016 at 7:51
  • No, thats not needed. Let me give you a sample; will post it in answer Commented Aug 24, 2016 at 8:11

1 Answer 1

1

As discussed in comments, please find below the code which is working fine for me:

self.addFlight = function (requestData) {

            var deferred = $q.defer();

            $http.post(baseUrl, requestData, {
                headers: {
                    'Content-Type': undefined,
                    'Accept': 'application/json'
                }
            })
              .success(function (data) {
                  deferred.resolve(data);
              }).error(function (msg, code) {
                  deferred.reject(msg);
              });

            return deferred.promise;
        };

And the requestData is:

var formData = new FormData();
formData.append("flight[name]", self.flightDetails.name);

formData.append("image", self.logoThumbnailData.data);

where logoThumbnailData.data is the actual file:

var fileData = element.files[0],
windowUrl = window.URL || window.webkitURL;

var objectUrl = windowUrl.createObjectURL(fileData);
self.logoThumbnailData = { data: fileData, url: objectUrl };

Your api action should look like:

public IHttpActionResult YourMethodName(HttpPostedFileBase image) 

"image" should be bound with your file if modal binding is proper, otherwise check in Request.Files

Sign up to request clarification or add additional context in comments.

2 Comments

In my case I am using multipart/form-data to post formdata to the server. The problem is without a form submit, Content-Type fails to send multipart/form-data which instead sends application/json. So it throws Unsupported Media Type error. To avoid that I have to use a form submit.
@AngelaAmarapala - Do you really need to set content-type as "multipart/form-data". Keep it 'Content-Type': undefined and when you submit form data, this will be sent as multipart/form-data with proper boundries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.