使用JS验证CSV(RFC 4180),(最好是角度)

时间:2015-01-21 21:29:30

标签: javascript angularjs validation csv

[重新制定的问题]

我有一个输入类型=文件,允许用户从磁盘中选择一个文件。实际上传过程已经正常工作:

upload.html:

<input type="file" file-upload accept=".csv" />

指令:

directive('fileUpload', ['$rootScope',
    function ($rootScope) {
        return {
            scope: true,
            link: function (scope, el, attrs) {
                el.bind('change', function (event) {
                    var file = event.target.files[0];
                    $rootScope.$broadcast('fileSelected', { file: file });
                });
            }
        };
    }

控制器:

$scope.uploadCSVData = {};
$scope.uploadCSVData.name = '';

$scope.submitUpload = function () {
$http({

    url: $api.$options.url + '/upload/list',
    method: 'POST',
    withCredentials: true,
    headers: {'Content-Type': 'multipart/form-data'},
    transformRequest: function (data) {
        var formData = new FormData();
        formData.append('data', angular.toJson($scope.uploadCSVData));
        formData.append('file' , $scope.file);
        return formData;
    }

现在我想添加一个方法来对该CSV文件的内容进行一些简单的验证。我已经阅读了多篇关于解析CSV字符串并验证它们的文章,但他们总是假设我有实际的字符串。

在我的情况下,我有一个文件 - 虽然我可以获得大量关于文件的元数据(例如最后编辑的日期,甚至文件大小) - 我似乎无法访问JS中的数据本身我可以验证它。

$scope.$on('fileSelected', function (event, args) {
    $scope.file = args.file;
    console.log($scope.file);
});

该对象如下所示:

File {
    lastModified: 1421877884000
    lastModifiedDate: Wed Jan 21 2015 17:04:44 GMT-0500 (Eastern Standard Time)
    name: "csv.csv"
    size: 5
    type: "application/vnd.ms-excel"
    webkitRelativePath: ""
}

它目前包含一个5个字母的字符串(仅用于测试),但我无法访问该字符串。

如何将文件内容放入一个我可以用JS验证的对象?

初步测试表明我可以在执行$ http POST之前执行$ http GET,但是$ http GET想要一个指向服务器上某个位置的URL。我在服务器上没有位置,因为用户正在使用输入字段直接获取文件。 那么如何将$ http GET指向已存储为$ scope.file的文件?

1 个答案:

答案 0 :(得分:0)

我找到了一个解决方案,但我不能保证它是多么普遍兼容。 (关于所有浏览器是否支持FileReader,似乎有些含糊不清。)

http://caniuse.com/#search=file

$scope.$on('fileSelected', function (event, args) {
    $scope.file = args.file;
    var reader = new FileReader();
    reader.onload = function(e){
        $scope.uploadCSVData.valid = $scope.validCSV(reader.result);
    };
    reader.readAsText($scope.file);
});

$scope.validCSV = function(text){
    // regex to test validity of text as CSV
    // returns string if valid, null if invalid
}
相关问题