简体   繁体   中英

How to send array of files from angular to php script?

I want to implement files uploading in my app. I use AngularJS and wrote method in controller to get all files from form input. In browser console I have an array with selected files, but when I send this array to backend it is empty. I send other data with the same method and I can read it in PHP script with no problems, only files array is empty.

This is method to get files from input and send it to backend:

 $scope.addFilesFunction = function() {
        $scope.filesList = document.getElementById('fileupload').files;
        var fd = new FormData();
        for (var i = 0; i < $scope.filesList.length; i++) {
             fd.append('file', $scope.filesList[i]);
        }
        Database.insert('file', {'files': fd}, function(response) {

        });
    };

And this is a piece of my PHP code:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$files = $request->files;

From: https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs

Its kinda hard to tell without all of the code, but it looks as though you aren't posting the actual files to PHP.

.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }
}]);

and

var file = $scope.myFile;
var uploadUrl = 'http://www.example.com/yourphpscript.php';
fileUpload.uploadFileToUrl(file, uploadUrl);

and then use your php script to handle any database magic you want to work. If you wanted to import an array of files, just pass in an array to fileUpload, and then iterate through your file array and append each with the FormData append.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM