【问题标题】:Print out file content after upload, AngularJS上传后打印出文件内容,AngularJS
【发布时间】:2014-08-25 11:38:05
【问题描述】:

编辑:我解决了。我写道:

$scope.result = data

在成功区。

我有一个可以上传文件的表格。我正在使用我在 github 上找到的 angular-file-upload 模型:https://github.com/danialfarid/angular-file-upload

上传完美。但是,在我上传文件后,我想返回文件内容,并在网站上打印出来,但我现在不知道如何将文件绑定到 $scope。

这是我的控制器:

as.controller('Marketing', function($scope, $http, $upload)
    {
        $scope.onFileSelect = function($files) {
            var file = $files[0];
            if (file.type.indexOf('image') == -1) {
                $scope.error = 'image extension not allowed, please choose a JPEG or PNG file.'            
            }
            if (file.size > 2097152){
                $scope.error ='File size cannot exceed 2 MB';
            }     
            $scope.upload = $upload.upload({
                url: 'partials/result.php',
                data: {},
                file: file,
            }).success(function(data, status, headers, config) {
                // file is uploaded successfully
                console.log(data);
            });
        }
    });

这是我的 PHP:

$filename = $_FILES['file']['tmp_name'];

if(($handle = fopen($filename, "r")) !== FALSE) {
    while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br/></p>\n";
        $row++;
        for($c = 0; $c < $num; $c++) {
            echo $data[$c] . "<br/>\n";
        }
    }
    fclose($handle);
}

这是我的 HTML:

<div ng-controller="Marketing">
<form class="well form-search" enctype="multipart/form-data">
    <input type="file" name="image" ng-file-select="onFileSelect($files)" >
</form>

<pre ng-model="result">
    {{result}}
</pre>

</div>

如您所见,我想将内容绑定到 $scope.result。

【问题讨论】:

    标签: javascript angularjs file


    【解决方案1】:

    由于您已经在应用程序中拥有文件,您只需要将它们绑定到$scope

    as.controller('Marketing', function($scope, $http, $upload)
        {
            $scope.onFileSelect = function($files) {
                var file = $files[0];
                if (file.type.indexOf('image') == -1) {
                    $scope.error = 'image extension not allowed, please choose a JPEG or PNG file.'            
                }
                if (file.size > 2097152){
                    $scope.error ='File size cannot exceed 2 MB';
                }     
                $scope.upload = $upload.upload({
                    url: 'partials/result.php',
                    data: {},
                    file: file,
                }).success(function(data, status, headers, config) {
    
                    // This is the file you've just successfully uploaded
                    $scope.file = file
    
                });
            }
        });
    

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 2015-09-28
      • 2012-06-12
      • 1970-01-01
      • 2012-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      相关资源
      最近更新 更多