简体   繁体   English

如何将文件数组从angular发送到php脚本?

[英]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. 我使用AngularJS并在控制器中编写了方法,以从表单输入中获取所有文件。 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. 我使用相同的方法发送其他数据,并且可以在PHP脚本中毫无问题地读取它,只有文件数组为空。

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: 这是我的PHP代码的一部分:

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

From: https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs 来自: 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. 如果没有所有代码,这很难说,但是似乎您没有将实际文件发布到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. 然后使用您的php脚本处理您要使用的任何数据库魔术。 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. 如果要导入文件数组,只需将一个数组传递给fileUpload,然后遍历文件数组并为每个数组添加FormData追加。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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