1

I am trying to upload an excel file in mvc using angular js. Following is my view code:

    <div class="browsebtn" ng-controller = "serviceablectrlr"><input type="file" id="dataFile" name="uploadFile" data-max-size="2097152" accept=".xls, .xlsx" onclick="$('#fileError').hide();" /> 
</div>
<input id="btnUploadExcel" type="button" value="Upload" ng-click="UploadConfirmation()" class="btn  btn-yellow" />

Following is my controller Code :

var app = angular.module('ProductCatalog');

app.controller('serviceablectrlr', function ($scope, $http) {

    var apiURL = $("#ProductCatalogApiUrl").val();
    var ClearFile = function () {
            $("#dataFile").val('');
        }


// pass file object and url to this method
$scope.UploadConfirmation = function () {
    alert("sana");
    var formData = new FormData();
    var totalFiles = document.getElementById("dataFile").files.length;
    for (var i = 0; i < totalFiles; i++) {
        var file = document.getElementById("dataFile").files[i];
        var ext = file.name.split(".")[1];
        if ((ext == "xls" || ext == "xlsx") && file.size < (Math.pow(1024, 3) * 2)) {
            formData.append("dataFile", file);

            $http({

                method: 'POST',
                url: apiURL + "/BulkInsertion",
                data: formData,
                dataType: 'json',
                headers: { 'Content-Type': undefined},
                transformRequest: angular.identity

            }).then(function successCallback(response) {
                if (response.data.ResponseData == 'Success') {
                    showToastrMessage('success', 'Offer saved successfully!');
                    $scope.data = {};
                }
                else {
                    alert('In error');
                    showToastrMessage('error', response.data.ResponseData);
                }
            },
            function errorCallback(response) {
            });

        }
        else {

        }
    }

}
});

And following is my MVC Controller code:

   public ResponseModel Post(
            HttpPostedFileBase dataFile
            )
        { }

The problem i am facing is that the HttpPostedFileBase is null even though i am sending the correct parameters.

I have referred to the following question which is exactly my problem other than I am working on excel file uploading.

HttpPostedFileBase is null when uploading files with Angular

Any help would be appreciated.

1 Answer 1

2

You need to write following code in your cshtml view

@using (Html.BeginForm("ActioName", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data" }))
{         
       <div>
            <input type="file" name="file" />
            <input type="submit" value="OK" class="button" />
        </div>       
}

In MVC controller

[HttpPost]
      public ActionResult UploadFile(HttpPostedFileBase myFile)
      {
        //Validate the fileType

        // Verify that the user selected a file
        if (file != null && file.ContentLength > 0)
        {
        //do something here...
        }
      }

In cae you want to do with angular js then use following code to post file

// pass file object and url to this method
this.uploadFileToUrl = function (file,  uploadUrl) { 
    return $http({
        method: 'POST',
        url: uploadUrl,
        headers: { 'Content-Type': undefined },
        transformRequest: function() {
            var formData = new FormData();
            if(file){
               formData.append("myFile", file); 
            }
            return formData;
        }
    })
}

Add this in WebApiConfig.Register():

this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
Sign up to request clarification or add additional context in comments.

6 Comments

@Sana, can you please check in request object -> Request.Files; just try to get the value of "Request.Files" in post method
Request.Files yielded no results it says while debugging it
@Sana, oh i got it.If you are truing to upload using angular then please change declaration of your controller method. parameter name should be "myFile" instead of file. It should work. I updated my answer
it is giving me this error now No MediaTypeFormatter is available to read an object of type 'HttpPostedFileBase' from content with media type 'multipart/form-data'.
@Sana I guess you need to add supported media type. i updated my answer.
|

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.