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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog