我试图将图片上传到我的PHP web-API。邮递员一切正常,如果我用密钥profilePicture做一个POST请求,并且作为一个文件的值(我的API在处理之前检查所有内容),图像被保存。 但是现在,我想用AngularJS上传,但我一直得到500响应。这是我的前端代码:(我需要清理代码,我知道,它现在关于功能)
<form class="updateUserInformation"
ng-submit="updateProfile(userData.display_name,
userData.profile_picture,
account.username)"
flex="100" layout="row" >
<div>
<input ng-model="userData.profile_picture" type="file">
<img src=""
width="150px" style="border-radius: 20px">
</div>
<div>
<md-input-container class="md-block">
<label>Schermnaam</label>
<input type="text" ng-model="userData.display_name" width="100%" required autofocus>
</md-input-container>
<div>
<md-button class="md-button md-primary md-raised" type="submit">Submit</md-button>
</div>
</div>
</form>
这是我的控制器:
controller('profileController', function($scope) {
$scope.updateProfile = function (display_name, profile_picture, id) {
console.log(profile_picture);
var xhr = new XMLHttpRequest();
var url = '';
xhr.open('PUT', url, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(JSON.stringify({displayName:display_name}));
var xhr2 = new XMLHttpRequest();
var url2 = '';
xhr2.open('POST', url2, true);
xhr2.setRequestHeader("Content-Type", "multipart/form-data");
xhr2.send(JSON.stringify({profilePicture:profile_picture}));
// location.reload();
}
});
答案 0 :(得分:0)
要使用Ajax上传文件,请使用FormData对象
var xhr2 = new XMLHttpRequest();
var url2 = '';
xhr2.open('POST', url2, true);
var data = new FormData();
data.append('profilePicture', profile_picture);// profile_picture is a File or a Blob
// don't set the Content-Type header, it will be set internally(when FormData is used)
xhr2.send(data);