使用angular上传文件的php后端

问题描述:

I got part of the file upload process to work, the only part I cannot figure out is the backend to save it in the db.

So my html...

<input type="file" name="file" id="thefile" multiple ng-files="getTheFiles($files)"/>
<input name="submit" type="submit" ng-click="uploadFiles()" value="Submit">

And here is the controller...

app.controller('import', function($scope, $http) {
    var formdata = new FormData();
    $scope.getTheFiles = function ($files) {
        angular.forEach($files, function (value, key) {
            formdata.append(key, value);
        });    
    };
    $scope.uploadFiles = function () {
            var request = {
                method: 'POST',
                url: '../submit.php',
                data: formdata,
                headers: {
                    'Content-Type': undefined
                }
            };

            // SEND THE FILES.
            $http(request)
                .success(function (d) {
                    alert(d);
                })
                .error(function () {
                });
        }
});

This seems to work, when I console.log(formdata) I get an object. But now, I need to save it in the DB and in the server. The only php code I tried was the usual way one would save a file...

if(isset($_FILES['file'])) {

    $file = rand(1000,100000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];
    $folder="uploads/";

    move_uploaded_file($file_loc,$folder.$file);
    $sql="INSERT INTO tbl_uploads(file,type,size) VALUES(?,?,?)";
    $statement = $conn->prepare($sql);
    $statement->execute(array($file,$file_type,$file_size));

But this doesn't do anything. I also am finding it hard to debug because my angular prints success but I can't echo on the server side since I'm making an http request to it.

What you're missing is that angular transforms your request data automatically, which you do not want with FormData.
You can stop this by adding transformRequest: angular.identity, to your request object.