使用angularjs在MVC中上传Excel文件。 HttpPostedFileBase是空的

我正在尝试使用angular度js在mvc上传一个excel文件。 以下是我的观点代码:

<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" /> 

以下是我的控制器代码:

 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 { } } } }); 

以下是我的MVC控制器代码:

  public ResponseModel Post( HttpPostedFileBase dataFile ) { } 

我面临的问题是即使我发送正确的参数HttpPostedFileBase为null。

我已经提到了以下问题,这正是我的问题,而不是我正在上传Excel文件。

使用Angular上传文件时,HttpPostedFileBase为null

任何帮助,将不胜感激。

您需要在cshtml视图中编写以下代码

 @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> } 

在MVC控制器

 [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... } } 

在cae你想要做angularjs然后使用下面的代码来发布文件

 // 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; } }) } 

将其添加到WebApiConfig.Register()

 this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));