Dima Grigoriev Dima Grigoriev - 1 month ago 5
AngularJS Question

Pass file to asp.net contoller using angular

i need upload file from

<input class="fromFileInput" id="VeryfyFromFileInput" type="file" fileread="fileContent" ng-click=uploadFile />


using angular

controller:

$scope.fileInformation = [];

$scope.uploadFile = function () {
$scope.fileModel = $('#VeryfyFromFileInput');
recordsService.passFile($scope.fileModel.context);
};


service:

this.passFile = function (data) {
return $http({
method: 'POST',
url: url + "/GetFile",
data: data,
headers: { 'Content-Type': 'application/json' }
});
};


To ASP.NET MVC controller

[HttpPost]
public void GetFile([FromBody] HttpRequestMessage file)
{

}


But i have always null, so which type of parametrs i must use instead of 'HttpRequestMessage '? Or maybe problem in JS side?

Answer

You cannot pass bytedata over the wire as application/json. One solution is to use a Form Data object and make the ajax call as a multipart/formdata. Use the following Ajax call.

         $.ajax({
                url: 'api/controller/action',
                processData: false,
                contentType: false,
                type: 'POST',
                data: formDataObject,
                success: function () {
                    alert('yay!');
                },
                error: function () {
                    alert('nay :c');
                }
            });

I used angular-ui file upload directive. I'm not sure if the way you're accessing it works, if it does then you can simply use the following syntax to add your file to FormData

var formDataObject = new FormData();
formDataObject.append('file', $scope.fileModel;

On the server use this snippet to access your data

 var filesReadToProvider = await Request.Content.ReadAsMultipartAsync();
 foreach (var stream in filesReadToProvider.Contents)
 switch (stream.Headers.ContentDisposition.Name)
                {
                    case "\"file\"":
                        byte[] fileData = await stream.ReadAsByteArrayAsync();
                        break;
                    default:
                        break;

                }

            }

For information on how to write a byte array as file to server follow: Write File to server

Good luck!