将上传的文件内容作为JSON返回

时间:2014-07-04 09:51:13

标签: javascript json angularjs

我正在使用angularjs上传文件。我正在使用我在github上找到的这个模型: https://github.com/danialfarid/angular-file-upload

上传效果很好。但是,在我上传文件后,我希望将文件内容作为JSON返回,然后使用Angular迭代JSON对象。但我不知道该怎么做。

这是我的代码:

$filename = $_FILES['file']['tmp_name'];
$csv = array_map('str_getcsv', file($filename));
foreach($csv as $c)
{
    echo str_replace(array('"', ';'), ' ', $c[0]) . "\n";
}
    //Return as JSON here? HOW?

这是我的控制器:

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);
            $scope.result = data;
        });
    }
});

我想要数据和JSON对象。我怎么能做到这一点?当我用PHP尝试json_encode时,它不起作用。

有谁可以帮我解决这个问题?

1 个答案:

答案 0 :(得分:0)

我相信这就是你正在寻找的东西

if(isset($_FILES["file"])){
    $fname = $_FILES['file']['tmp_name'];
    // ...
    if(move_uploaded_file($fname, "uploads/" . $fname)){

        // this way
        $csv = file_get_contents($fname);
        $array = array_map("str_getcsv", explode("\n", $csv));
        echo json_encode($array);

        // or this way; have in mind delimiter
        $row = str_getcsv($csv, "\n");
        $length = count($row);
        for($i = 0; $i < $length; $i++){
            $data = str_getcsv($row[$i], ";");
            $array[] = $data; 
        }
        echo json_encode($array);
    }
    // ...
}
相关问题