dongpeng8994
dongpeng8994
2016-10-12 15:40
浏览 73
已采纳

使用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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyejv820598
    douyejv820598 2016-10-12 15:44
    已采纳

    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.

    点赞 评论

相关推荐