error505 error505 - 3 months ago 131
AngularJS Question

IFormFile is always empty in Asp.Net Core WebAPI

I have a problem here when I am trying to push data with angularjs controller. But what ever I do (IFormFile file) is always empty. There are only some examples with razor syntax but no examples how to do it with angular or jquery.


<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';

.directive('ngFiles', ['$parse', function ($parse) {

function fn_link(scope, element, attrs) {
var onChange = $parse(attrs.ngFiles);
element.on('change', function (event) {
onChange(scope, { $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();'POST', url, true);
xhr.setRequestHeader("Content-Type", "undefined");
} core webapi:

public async Task<IActionResult> PostProductProjectFile(IFormFile file)
if (!ModelState.IsValid)
return BadRequest(ModelState);

return ...;

I have also tried to form data as it is constructed when you post it with razor syntax something like this

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

Also instead of formData to provide raw file as I wrote in comment. But still nothing happens


This is how to do it with 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]);

                $"/api/Files/", data, {
                    headers: { 'Content-Type': undefined },
                    transformRequest: angular.identity
                }).success(function (data, status, headers, config) {

                }).error(function (data, status, headers, config) {