Search code examples
javascriptc#angularjsasp.net-web-aping-file-upload

Can't upload image file from ng-file-upload to web api


I am using this directive (ng--file-upload) to upload image.
I need to include image file to a POST to ASP.NET Web API but I don't have any success.
This is my method on server:

public async Task<HttpResponseMessage> SaveData([FromBody]PostModel data)

When I post data (from js angular) all data are here except uploaded file:

$http({
            method: 'POST',
            url: path,
            data: data,
            file: photoFile
        }).then(function...

I tried to put it in data also but it is always null.
How can I post and get image file on web api?

As a response I am getting:

"Invalid 'HttpContent' instance provided. It does not have a content type header starting with 'multipart/'.
 Parameter name: content"

On this line:

var provider = new MultipartMemoryStreamProvider();
            await Request.Content.ReadAsMultipartAsync(provider);

var data = {            
            "Username": $scope.username,
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined }
        };

        var fd = new FormData();
        fd.append('file', $scope.photoFile);

        $http({
            method: 'POST',
            url: 'path', fd, 
            data: data
        }).the

Solution

  • Use FormData API:

    html:

    <div class="button" ngf-select="upload($file)">Upload on file select</div>
    

    controller:

     $scope.upload = function (file) {
        var fd = new FormData();
        fd.append('file', file);
    
        //Append other data
        //angular.forEach(data,function(v,k){
        //    fd.append(k,v);
        //});
    
        $http.post('your-upload-url', fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .then(function(res){
            // get upload res
        });
    };