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

kyo*_*kyo 12 javascript php laravel angularjs laravel-5


我有

在此输入图像描述

浏览文件按钮

<input type="file" upload-files multiple />
Run Code Online (Sandbox Code Playgroud)

创建按钮

<button class="btn btn-link" ng-click="store()" >Create</button>
Run Code Online (Sandbox Code Playgroud)

指示

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] });
                }
            });
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

收听所选文件

$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);
    });

});
Run Code Online (Sandbox Code Playgroud)

发布数据和选定的文件.

$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);
    });
};
Run Code Online (Sandbox Code Playgroud)

结果

在我的控制台中,我没有看到我的文件在后端传递给我的控制器.

array:1 [
  "model" => "{"type":"wedding"}"
]
Run Code Online (Sandbox Code Playgroud)

问题

我忘记了哪些步骤?

如何进行并进一步调试?


Chr*_*ris 1

这里给你一些建议:

  1. 进行Content-type设置以multipart/form-data将内容类型设置为......“其中包含某些部分,请确保正确获取它”之类的东西。
  2. 使用axios。这是一个工作示例(如果您没有使用 Axios,这个示例也很好)。Axios 上传文件示例