Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload multiple files via AngularJS to Laravel Controller


I have

enter image description here

Browse files button

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

Create Button

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

Directive

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

Listen for the file selected

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

});

Post data and selected files.

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

Result

In my console, I don't see my files got pass on to my controller in the back-end.

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

Questions

What steps did I forget?

How would one go about and debug this further ?


like image 450
code-8 Avatar asked Mar 23 '17 16:03

code-8


3 Answers

I've done several angular 1 projects and also find it is not simple to upload files via $http api. Hope below code snippet which i used in my projects may help you.

$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() {
    // ...
  });
};
like image 79
yixiang Avatar answered Oct 30 '22 13:10

yixiang


Here some suggestions for you:

  1. Make the Content-type sets to multipart/form-data to set the content type to something like.... "it has some part in it, please make sure you get it properly" thing.
  2. Use Axios. Here's a working examples (if you didn't use Axios, this example are good too). Example to Axios on Uploading File.
like image 1
Chris Qiang Avatar answered Oct 30 '22 14:10

Chris Qiang


You can use FormData instead

var formData = new FormData();

  formData.append('model[var]', $scope.var);

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

 // POST REQUEST MUST BE:
  $http.post('url', formData, {
    transformRequest: angular.identity,  //It is for allowing files
    headers: {'Content-Type': undefined}
    }).then(function(response) 
  {
    // verify if response get 200
  });
like image 1
Luis Andrés Juárez Sandoval Avatar answered Oct 30 '22 14:10

Luis Andrés Juárez Sandoval