使用angularjs在MVC中上载Excel文件。HttpPostedFileBase为空
我正在尝试使用angular js在mvc中上传一个excel文件。以下是我的查看代码:使用angularjs在MVC中上载Excel文件。HttpPostedFileBase为空,angularjs,asp.net-mvc,excel,file-upload,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 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" />
我面临的问题是,即使我发送了正确的参数,HttpPostedFileBase也是空的
我提到了以下问题,这正是我的问题,而不是我的excel文件上传工作
任何帮助都将不胜感激。您需要在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>
}
在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()
:
@萨娜,你能签入请求对象->请求文件吗;只需尝试在PostMethodRequest.Files中获取“Request.Files”的值,就可以在调试时得到它所说的结果it@Sana,哦,我明白了。如果你想用angular上传,请更改控制器方法的声明。参数名称应为“myFile”而不是“file”。它应该会起作用。我更新了我的回答。现在没有MediaTypeFormatter可用于从媒体类型为“multipart/form data”的内容中读取类型为“HttpPostedFileBase”的对象。我想您需要添加支持的媒体类型。我更新了我的答案。
@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>
}
[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...
}
}
// 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;
}
})
}
this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));