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

时间:2017-08-04 10:51:39

标签: angularjs asp.net-mvc excel file-upload

我正在尝试使用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文件上传。

HttpPostedFileBase is null when uploading files with Angular

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

您需要在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中你想要使用角度js然后使用以下代码发布文件

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