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

使用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条回答 默认 最新

  • 普通网友 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化