0

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
1
  • You can use Upload.upload() service to send the file. Read the docs. Commented May 26, 2016 at 12:08

1 Answer 1

1

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
    });
};
Sign up to request clarification or add additional context in comments.

5 Comments

But how can I get the file on Web API side?
Sorry, I thought it was a angular issue....Not good at c#, but you can check this
I updated question with sending data as you suggest do you maybe have idea why I am getting error from question?
An obvious error is that, fd is just the data you thought, like `$http({...,data:fd,..}).
don't put transformRequest and headers in data, please refer this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.