Nikhil Nikhil - 16 days ago 4
Javascript Question

How to get csv file object from zipobject in jszip and angularjs

I am trying to get csv file object from zipobject which i extracted from a zip file using jszip.But Now i am not able to read the actual csv file from this zipobject.Can anybody help?
this is my zipobject,enter image description here



<!DOCTYPE html>
<html data-ng-app="myApp">

<head>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script data-require="jszip@2.4.0" data-semver="2.4.0" src="https://cdn.rawgit.com/Stuk/jszip/v2.4.0/dist/jszip.js"></script>
</head>

<body data-ng-controller="testController">


<div>
<input type="file" name="archiveUpload" id="archiveUpload01">
</div>

<script>
angular
.module('myApp', [])
.run(function($rootScope) {
$rootScope.title = 'myTest Page';
})
.controller('testController', ['$scope', '$q',
function($scope, $q) {

$scope.extractArchive = function(zipfile) {
var dfd = $q.defer();
var reader = new FileReader();

reader.onerror = dfd.reject.bind(dfd);
reader.onload = function(e) {
if (!reader.result) dfd.reject(new Error("Unknown error"));

var zip = new JSZip(reader.result);
return dfd.resolve(zip);
};
reader.readAsArrayBuffer(zipfile);
return dfd.promise;
}

function onArchiveChange(evt) {
var target = evt.dataTransfer || evt.target;
var file = target && target.files && target.files[0];
$scope.extractArchive(file)
.then(function(zipFile) {
console.log(zipFile)
})
}

angular.element(document.querySelector('#archiveUpload01')).on('change', onArchiveChange);


}
])
</script>
</body>

</html>





This is my code.

Answer

Use the async method to get a promise of the content (which behave like $q):

zip.file("Positions.csv").async("text")
.then(function success(txt) {
  console.log("csv is", txt);
}, function error(e) {
  console.error(e);
});

Edit: the code above is for JSZip v3, you use JSZip v2:

var txt = zip.file("Positions.csv").asText();
console.log("csv is", txt);

zip.file("Positions.csv") will give you the ZipObject you show on your image.

Edit 2: extractArchive, written for JSZip v3, looks like:

$scope.extractArchive = function(zipfile) {
  return JSZip.loadAsync(zipfile); // JSZip v3 can read Blobs and Files
}; // returns a promise of a JSZip instance

You can then chain other promises:

$scope.extractArchive(zipfile).then(function (zip) {
  return zip.file("Positions.csv").async("arraybuffer");
}).then(function (buf) {
  var blob = new Blob([buf]);
  // ...
})
Comments