我想用angularjs上传文件和其他数据。我使用FormData,但我从服务器端收到空白数组。
这是我的表单
<form ng-submit="beatSubmit()" name="beatform" enctype="multipart/form-data">
<input type="text" id="beat-name" ng-model="beatData.title" required="required" />
<input type="file" id="image" file-model="image" />
<input type="file" id="tagged_file" file-model="tagged_file" accept="audio/mp3" />
<input type="file" id="untagged-beat" file-model="untagged_file" accept="audio/mp3" />
<input type="text" class="form-control" id="price1" ng-model="beatData.price1">
</form>
这是我的Controller和FileModel指令
app.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
// This is controller part in another file
$scope.beatSubmit = function(){
var image = $scope.image;
var tagged_file = $scope.tagged_file;
var untagged_file = $scope.untagged_file;
var response = BEAT.uploadBeat($scope.beatData,image,tagged_file,untagged_file);
response.success(function(response){
console.log(response);
});
}
这是我的服务
uploadBeat:function(data,image,tagged_file,untagged_file){
var fd = new FormData();
fd.append('image', image);
fd.append('tagged_file', tagged_file);
fd.append('untagged_file', untagged_file);
angular.forEach(data, function(value, key) {
fd.append(key,value);
});
console.log(fd); // fd is null , I don't know why?
var req = {
method: 'POST',
transformRequest: angular.identity,
url: 'api/upload_music',
data: fd,
headers:{
'Content-Type': undefined,
}
}
return $http(req);
}
当我从服务器端获取这些数据时它将返回null。我花了更多的时间来解决这个问题,但我没有得到任何解决方案。如果有人知道请帮助我。提前谢谢。
答案 0 :(得分:0)
将此标题详细信息添加到$ http
$http({
method: 'POST',
url: '',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept':'*/*',
'Content-type':'application/x-www-form-urlencoded;charset=utf-8'
},
params:data,
timeout:4000
});
Laravel不允许在没有相同域策略的情况下提交ajax请求
答案 1 :(得分:0)
我发现了一个错误,我必须删除enctype =&#34; multipart / form-data&#34;从形式。