Dima Grigoriev Dima Grigoriev - 1 year ago 89
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


$scope.fileInformation = [];

$scope.uploadFile = function () {
$scope.fileModel = $('#VeryfyFromFileInput');


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

To ASP.NET MVC controller

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 Source

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.

                url: 'api/controller/action',
                processData: false,
                contentType: false,
                type: 'POST',
                data: formDataObject,
                success: function () {
                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();



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

Good luck!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download