IFormFile在Asp.Net Core WebAPI中始终为空
我在尝试使用angularjs控制器推送数据时遇到问题。但是我所做的(IFormFile文件)总是空的。只有一些使用razor语法的示例,但是没有使用angular或jquery的示例。
HTML:
<form class="form-body" enctype="multipart/form-data" name="newFileForm" ng-submit="vm.addFile()"><input type="file" id="file1" name="file" multiple ng-files="getTheFiles($files)"/></form>
指示:
(function() {'use strict';
angular
.module('app')
.directive('ngFiles', ['$parse', function ($parse) {
function fn_link(scope, element, attrs) {
var onChange = $parse(attrs.ngFiles);
element.on('change', function (event) {
onChange(scope, { $files: event.target.files });
});
};
return {
link: fn_link
};
}]);
})();
控制者
var formdata = new FormData(); $scope.getTheFiles = function ($files) {
angular.forEach($files, function (key, value) {
formdata.append(key, value);
});
};
vm.addFile = function () {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-Type", "undefined");
xhr.send(formdata);
}
ASP.NET核心WebAPI:
[HttpPost] public async Task<IActionResult> PostProductProjectFile(IFormFile file)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
....
return ...;
}
我还尝试过使用formdata,因为它是在您使用razor语法发布时构造的。像这样:
dataService.addFile(formdata, { contentDisposition: "form-data; name=\"files\"; filename=\"C:\\Users\\UserName\\Desktop\\snip_20160420091420.png\"",
contentType: "multipart/form-data",
headers: {
"Content-Disposition": "form-data; name=\"files\"; filename=\"C:\\Users\\UserName\\Desktop\\snip_20160420091420.png\"",
'Content-Type': "image/png"
},
fileName: "C:\\Users\\UserName\\Desktop\\snip_20160420091420.png",
name: "files",
length : 3563
}
也代替formData提供原始文件,如我在评论中所写。但是仍然没有任何反应
回答:
这是使用angularjs的方法:
vm.addFile = function () { var fileUpload = $("#file").get(0);
var files = fileUpload.files;
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$http.post("/api/Files/", data, {
headers: { 'Content-Type': undefined },
transformRequest: angular.identity
}).success(function (data, status, headers, config) {
}).error(function (data, status, headers, config) {
});
}
在网络Api中:
[HttpPost]public async Task<IActionResult> PostFile()
{
//Read all files from angularjs FormData post request
var files = Request.Form.Files;
var strigValue = Request.Form.Keys;
.....
}
或像这样:
[HttpPost] public async Task<IActionResult> PostFiles(IFormCollection collection)
{
var f = collection.Files;
foreach (var file in f)
{
//....
}
}
以上是 IFormFile在Asp.Net Core WebAPI中始终为空 的全部内容, 来源链接: utcz.com/qa/428969.html