1110
1110

Reputation: 6839

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

Upvotes: 0

Views: 392

Answers (1)

Yin Gang
Yin Gang

Reputation: 1443

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
    });
};

Upvotes: 1

Related Questions