gpt4 book ai didi

javascript - 通过 AngularJS 上传多个文件到 Laravel Controller

转载 作者:可可西里 更新时间:2023-11-01 02:09:43 26 4
gpt4 key购买 nike


我有

enter image description here

浏览文件按钮

<input type="file" upload-files multiple />

创建按钮

<button class="btn btn-link" ng-click="store()" >Create</button>

指令

myApp.directive('uploadFiles', function () {
return {
scope: true,
link: function (scope, element, attrs) {
element.bind('change', function (event) {
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
scope.$emit("seletedFile", { file: files[i] });
}
});
}
};
});

监听选择的文件

$scope.files = [];
$scope.$on("seletedFile", function (event, args) {

console.log("event is ", event);
console.log("args is ", args);

$scope.$apply(function () {
$scope.files.push(args.file);
});

});

发布数据和选定的文件。

$scope.store = function() {

$scope.model = {
name: $scope.name,
type: $scope.type
};

$http({
method: 'POST',
url: '/image/store',
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
console.log("data coming into the transform is ", data);
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
for (var i = 0; i < data.files; i++) {
formData.append("file" + i, data.files[i]);
}
return formData;
},

data: { model: $scope.model, files: $scope.files }

})


.then(function successCallback(response) {
console.log("%cSuccess!", "color: green;");
console.log(response);
$scope.refresh();
$scope.showModal = false;
}, function errorCallback(response) {
console.log("%cError", "color: red;");
console.log(response);
});
};

结果

在我的控制台中,我没有看到我的文件在后端传递到我的 Controller 。

array:1 [
"model" => "{"type":"wedding"}"
]

问题

我忘记了什么步骤?

如何进一步调试它?


最佳答案

我做过几个angular 1的项目,也发现通过$http api上传文件并不简单。希望我在我的项目中使用的以下代码片段可以帮助您。

$scope.store = function() {
var formData = new FormData();

// add normal properties, the name should be the same as
// what you would use in a html form
formData.append('model[name]', $scope.name);
formData.append('model[type]', $scope.type);

// add files to form data.
for (var i = 0; i < $scope.files; i++) {
formData.append('file' + i, $scope.files[i]);
}

// Don't forget the config object below
$http.post('/image/store', formData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).then(function() {
// ...
});
};

关于javascript - 通过 AngularJS 上传多个文件到 Laravel Controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42981232/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com