Uploading Excel File in MVC using angularjs. HttpPostedFileBase is empty

匿名 (未验证) 提交于 2019-12-03 09:14:57

问题:

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:

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")); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!