Загрузка файла Excel в MVC с помощью angularjs. HttpPostedFileBase пуст
Я пытаюсь загрузить файл Excel в MVC, используя угловой JS. Ниже приведен код моего просмотра:
<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 имеет значение null при загрузке файлов с Angular
Любая помощь будет оценена.
1 ответ
Решение
Вам нужно написать следующий код в вашем представлении 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 вы хотите сделать с Angular 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"));