2016-08-25 166 views
1

我没有太多的前端经验,所以请耐心等待。在浏览器中加载JSON文件

我在浏览器中有一个本地的Angular应用程序(无后端),我想上传一个JSON文件,以便我可以在图上显示上传的数据。由于我不知道Angular的fs.readFile是否可以,我选择了ng-file-upload以很好的方式(从文件浏览器)加载文件。让我知道,如果它不是正确的工具,但...

所以我已经从官方JS Fiddle on the repo复制代码。不得不稍微修改它以允许我上传任何内容 - 删除验证。

var app = angular.module('app', ['ngFileUpload']); 

app.controller('fileUploader', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) { 
    $scope.uploadFiles = function(file, errFiles) { 
    $scope.f = file; 
    $scope.errFile = errFiles && errFiles[0]; 
    if (file) { 
     file.upload = Upload.upload({ 
     url: 'https://angular-file-upload-cors-srv.appspot.com/upload', 
     data: {file: file} 
     }); 

     file.upload.then(function (response) { 
     $timeout(function() { // don't know why this timeout 
     $scope.fileReady = true; 
     file.result = response.data; 

     // can't figure out what to do with this!!! 
     console.log('response.data:\n', JSON.stringify(response.data.result, null, 2)); 
     }); 
     }, function (response) { 
     if (response.status > 0) 
      $scope.fileError = response.status + ': ' + response.data; 
     }); 
    } 
    }; 
}]); 

的反应出来作为一个对象,我不能做与:

[ 
    { 
    "fieldName": "file", 
    "name": "my-awesome-data.json", 
    "size": "364077" 
    } 
] 

我如何获得已上载的实际数据/解析JSON文件?

+1

是啊,也许是'NG-文件uploader'不是本地文件的工具。这是一个更简单的解决方案:http://stackoverflow.com/questions/26165919/filereader-not-loading-file-properly-using-angularjs – sakovias

回答

2

试图让使用$ http.get像文件内容:

$http.get(response.data).success(function(data) { 
    console.log(data); 
});