如何使用Angular将数据作为表单数据发布

时间:2016-01-19 16:52:05

标签: angularjs post angular-http

我想将一个头像发送到我的服务器,但我有这个错误"你必须包含“头像”#39; POST表单数据中的文件var。"

function getPictureSuccess(imageData) {
    var image = "data:image/jpeg;base64," + imageData;
    $scope.avatar = image;
}

$http({
    url: api_url + 'userplus/avatar_upload/?key=' + api_key + '&cookie=' + dataCookie,
    method:"POST",
    headers : {'Content-Type': 'application/x-www-form-urlencoded'},
    data: {avatar: avatar}
});

2 个答案:

答案 0 :(得分:0)

data: {avatar: avatar}更改为data: {avatar: $scope.avatar}

答案 1 :(得分:0)

try

imgURI = "data:image/jpeg;base64," + imageData;

var FD = new FormData();
FD.append('image', dataURItoBlob(imgURI), 'image.jpg'); // "image" This is what you get at server side so change it accord inly 
FD.append("Other Param", 'other Param value ') // other parameter needed to post 


$http.post('Your Url', DataObj, {
    headers: {
        'Content-Type': undefined
    },
    transformRequest: angular.identity
}).then(function(responce) {
    responce.data;
})

// And here is your helper function 


function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString = atob(dataURI.split(',')[1]);
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

    var ab = new ArrayBuffer(byteString.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    var bb = new Blob([ab], {
        "type": mimeString
    });
    return bb;
}