无法将图像文件从ng-file-upload上传到web api

时间:2016-05-26 09:22:47

标签: javascript c# angularjs asp.net-web-api ng-file-upload

我正在使用此指令(ng--file-upload)上传图片 我需要将图像文件包含在POST到ASP.NET Web API中,但我没有取得任何成功。
这是我在服务器上的方法:

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

当我发布数据时(来自js angular),所有数据都在这里,除了上传的文件:

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

我也尝试将其放入数据中,但它始终为空 如何在web api上发布和获取图像文件?

作为回应我得到了:

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

在这一行:

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 个答案:

答案 0 :(得分:1)

使用FormData API

HTML:

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

控制器:

 $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
    });
};
相关问题