【问题标题】:AngularJS image upload with PHP使用 PHP 上传 AngularJS 图像
【发布时间】:2020-05-02 04:34:50
【问题描述】:

我以前做过这个,但现在它不起作用,我不知道到底哪里出了问题。

我正在尝试通过将图像传递给 PHP 文件来使用 Angularjs 上传图像。但是由于某种原因,图像没有传递给 PHP 文件。

我的表格:

    <form ng-submit="addImage()" id="addImageForm" class="collapse">

         <div class="form-group">
             <label for="newImage">Choose image</label><br>
             <input type="file" file-input="files" onchange="angular.element(this).scope().setFile(this)">
         </div>
        <input type="submit" class="btn btn-success" value="Add">

    </form>

我的 angularjs 指令似乎工作得很好:

//File upload
app.directive("fileInput", function ($parse) {
return{
    link: function ($scope, element, attrs) {
        element.on("change", function (event) {
            var files = event.target.files;
            console.log(files[0].name);
            $parse(attrs.fileInput).assign($scope, element[0].files);
            $scope.$apply();
        });
    }
};
});

我的控制器:

//Get image name
$scope.setFile = function (element) {
    $scope.$apply(function ($scope) {
        $scope.theFile = element.files[0];
    });
};

//Upload image
$scope.addImage = function () {
    var form_data = new FormData();

    angular.forEach($scope.files, function (file) {
        form_data.append('file', file);
    });

    $http.post(
            "handlers/add_image.php",
            form_data,
            {transformRequest: angular.identity, headers: {'Content-Type': undefined, 'Process-Data': false}}
    ).success(function (response) {
        $scope.response = response;

    });
};

我的 PHP:

<?php
if(!empty($_FILES){
echo "There is a file!";
}else{
echo "There is no file";
}

【问题讨论】:

    标签: javascript php angularjs


    【解决方案1】:

    改变

    <input type="file" file-input="files" onchange="angular.element(this).scope().setFile(this)">
    

    收件人:

    <input type="file" name="files" onchange="angular.element(this).scope().setFile(this)">
    

    一个不错的example here

    【讨论】:

    • 没有改变任何东西 :-(
    • 使用我在回答中给出的代码,并确保 angular.js 存在于您的文件中。
    猜你喜欢
    • 2014-07-11
    • 2015-06-14
    • 2015-06-29
    • 1970-01-01
    • 2016-04-22
    • 2016-03-26
    • 1970-01-01
    • 2015-08-13
    • 2018-06-04
    相关资源
    最近更新 更多