Extract uploaded file using adm zip - javascript

I am trying to get the list of files in a uploaded file using adm-zip. As we cant get the path of the uploaded file , iam trying to convert the zip into a Buffer and pass it to the adm-zip. But zip.getEntries(); its not giving me the list of files.
checkZipFiles(){
var AdmZip = require("adm-zip");
var filesInput = document.querySelector('input[type="file"]').files[0];
var res;
var zip = new AdmZip(filesInput);
console.log(' zip is '+JSON.stringify(zip));
var zipEntries = zip.getEntries();
console.log(' zipEntries is '+zipEntries);
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.toString()); // outputs zip entries information
if (zipEntry.entryName == "my_file.txt") {
console.log(zipEntry.data.toString('utf8'));
}
});
var reader = new FileReader();
reader.readAsArrayBuffer(filesInput);
var bytes,buf ;
reader.onloadend = function(e){
var readLen=e.target.result.byteLength;
var arrayBuffer = reader.result
bytes = new Uint8Array(arrayBuffer);
console.log('insidebytes is '+bytes);
buf = new Buffer(e.target.result.byteLength);
for (var i = 0; i < buf.length; ++i) {
buf[i] = bytes[i];
}
console.log(e.target.result.byteLength+' length is '+bytes.byteLength);
var myZip = e.target.result;
console.log('bytes is '+bytes);
console.log('buf is '+buf);
zip = new AdmZip(buf);
// console.log(zip+' reader ');
var zipEntries = zip.getEntries();
console.log(' zip is '+zipEntries);
}
}
When i print the buffer it prints something like below , with the file name inside the zip.
121832 length is 121832
}+����Y���L�]��%:����_����ld� ��c{\��h7���L��e33�\"ԅտ׉��v�˕3�-��^�'�Ҁ霗�^�p�q�W��������vްR�����akny���Egr����G�%1/���Wer����\d���A�upR�L����up�jemF���� ��k9y��^Ն;h�1:ca delete.txt
�-�-F1p[
But AdmZip gives below error. Is the issue with the buffer or AdmZip not able to read the buffer?
Uncaught Invalid END header (bad signature) mainHeader.js?4281:35

Related

How to convert base64 byte data into downloadable pdf file?

I have an encoded base64 data from an API response and stored in a variable encodedBase64.
let encodedBase64 = 'some base64 encoded long data';
function base64ToArrayBuffer(base64) {
var binaryString = window.atob(base64);
console.log('binaryString ', binaryString);
var binaryLen = binaryString.length;
var bytes = new Uint8Array(binaryLen);
for (var i = 0; i < binaryLen; i++) {
var ascii = binaryString.charCodeAt(i);
bytes[i] = ascii;
}
return bytes;
}
function saveByteArray(reportName, byte) {
var blob = new Blob([byte], {type: "application/pdf"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = reportName;
link.download = fileName;
link.click();
};
var sampleArr = base64ToArrayBuffer(encodedBase64);
saveByteArray("Sample Report", sampleArr);
after executing this code i am able to download pdf file names SampleReport.pdf but when i open this it is showing Failed to load PDF document. error
what is the wrong in my code ?
difficult to get it done using front end side
but it can be done easily using Nodejs using the following code.
fs.writeFile('pdfFileName.pdf', base64DataString, {encoding: 'base64'}, error => {
if (error) {
throw error;
} else {
console.log('buffer saved!');
}
});

Angular convert multiple Files into base64 string

I try to convert multiple files into multiple base64 strings.
But somehow my reader only spits out the same file over and over again. Anyone an Idea how to fix it?
handleFileSelect(evt) {
var files = evt.target.files;
var file = files[0];
for (let item of files) {
this.postData.name = item.name;
this.postData.type = item.type;
var reader = new FileReader();
reader.onload = this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(item);
}
}
_handleReaderLoaded(readerEvt, item) {
var binaryString = readerEvt.target.result;
this.base64textString = btoa(binaryString);
this.postData.base64 = this.base64textString;
this.saveToDB();
this.image = "data:image;base64, ";
}

Reading Excel file using SheetJs - Javascript

I am trying to read Excel file using SheetJs
But getting following error.
Uncaught TypeError: Cannot read property '0' of undefined
Here is my file handler function
function handleFileSelect(evt) {
//Get the files from Upload control
var files = evt.target.files;
var i, f;
//Loop through files
for (i = 0, f = files[i]; i != files.length; ++i) {
var reader = new FileReader();
var name = f.name;
reader.onload = function (evt) {
var data = evt.target.result;
var result;
/* convert from workbook to array of arrays */
var first_worksheet = data.Sheets[data.SheetNames[0]];
var data = XLSX.utils.sheet_to_json(first_worksheet, {header:1});
alert(result[0].Column1);
};
reader.readAsArrayBuffer(f);
}
}
You need to first read this data as an XLSX sheet first (Refer page 11)
workbook = XLSX.read(data, {type: 'binary'});
Followed by getting sheetnames from workbook (page 13)
var first_sheet_name = workbook.SheetNames[0];

Push ArrayBuffer in Array for constructing a Blob

I've got an array of URLs [URL1, URL2, URL3,...] : each element is a link to one of the chunks of the same file. Each chunk is separately encrypted, with the same key as all the other chunks.
I download each chunk (in a forEach function) with a XMLHttpRequest. onload :
each chunk is first decrypted
then each chunk is converted to an ArrayBuffer (source)
each ArrayBuffer is pushed to an array (source)
when the three first steps are done for each chunk (callback by a var incremented on step#1 === the array.length), a blob is constructed with the array
the blob is saved as file with FileReader API & filesaver.js
If it's a one chunk's file, everything works fine.
But with multiple chunks, steps #1 & #2 are ok, but only the last ArrayBuffer seems to be pushed to the array. What am I missing?
Below my code
// var for incrementation in forEach funtion
var chunkdownloaded = 0;
// 'clearfileurl' is the array of url's chunks :[URL1, URL2, URL3,...]
clearfileurl.forEach(function(entry) {
var xhr = new XMLHttpRequest();
var started_at = new Date();
xhr.open('GET', entry, true);
xhr.responseType = 'text';
// request progress
xhr.onprogress = function(pe) {
if (pe.lengthComputable) {
downloaderval.set((pe.loaded / pe.total) * 100);
}
};
// on request's success
xhr.onload = function(e) {
if (this.status == 200) {
chunkdownloaded+=1;
var todecrypt = this.response;
// decrypt request's response: get a dataURI
try {
var bytesfile = CryptoJS.AES.decrypt(todecrypt.toString(), userKey);
var decryptedfile = bytesfile.toString(CryptoJS.enc.Utf8);
} catch(err) {
console.log (err);
return false;
}
//convert a dataURI to a Blob
var MyBlobBuilder = function() {
this.parts = [];
}
MyBlobBuilder.prototype.append = function(dataURI) {
//function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
// var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
this.parts.push(ab);
console.log('parts', this.parts)
this.blob = undefined; // Invalidate the blob
}
MyBlobBuilder.prototype.getBlob = function() {
if (!this.blob) {
console.log (this.parts);
this.blob = new Blob(this.parts);
}
return this.blob;
};
var myBlobBuilder = new MyBlobBuilder();
myBlobBuilder.append(decryptedfile);
// if all chunks are downloaded
if (chunkdownloaded === clearfileurl.length) {
// get the blob
var FinalFile = myBlobBuilder.getBlob();
// launch consturction of a file with'FinalFile' inside FileReader API
var reader = new FileReader();
reader.onload = function(e){
// build & save on client the final file with 'file-saver' library
var FileSaver = require('file-saver');
var file = new File([FinalFile], clearfilename, {type: clearfiletype});
FileSaver.saveAs(file);
};
reader.readAsText(FinalFile);
} else {
console.log('not yet');
}
}
};
// sending XMLHttpRequest
xhr.send();
});
You need to take out the declaration of MyBlobBuilder, try this:
// var for incrementation in forEach funtion
var chunkdownloaded = 0;
//convert a dataURI to a Blob
var MyBlobBuilder = function() {
this.parts = [];
}
MyBlobBuilder.prototype.append = function(dataURI, index) {
//function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
// var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
this.parts[index] = ab;
console.log('parts', this.parts)
this.blob = undefined; // Invalidate the blob
}
MyBlobBuilder.prototype.getBlob = function() {
if (!this.blob) {
console.log (this.parts);
this.blob = new Blob(this.parts);
}
return this.blob;
};
var myBlobBuilder = new MyBlobBuilder();
// 'clearfileurl' is the array of url's chunks :[URL1, URL2, URL3,...]
clearfileurl.forEach(function(entry, index) {
var xhr = new XMLHttpRequest();
var started_at = new Date();
xhr.open('GET', entry, true);
xhr.responseType = 'text';
// request progress
xhr.onprogress = function(pe) {
if (pe.lengthComputable) {
downloaderval.set((pe.loaded / pe.total) * 100);
}
};
// on request's success
xhr.onload = function(e) {
if (this.status == 200) {
chunkdownloaded+=1;
var todecrypt = this.response;
// decrypt request's response: get a dataURI
try {
var bytesfile = CryptoJS.AES.decrypt(todecrypt.toString(), userKey);
var decryptedfile = bytesfile.toString(CryptoJS.enc.Utf8);
} catch(err) {
console.log (err);
return false;
}
myBlobBuilder.append(decryptedfile, index);
// if all chunks are downloaded
if (chunkdownloaded === clearfileurl.length) {
// get the blob
var FinalFile = myBlobBuilder.getBlob();
// launch consturction of a file with'FinalFile' inside FileReader API
var reader = new FileReader();
reader.onload = function(e){
// build & save on client the final file with 'file-saver' library
var FileSaver = require('file-saver');
var file = new File([FinalFile], clearfilename, {type: clearfiletype});
FileSaver.saveAs(file);
};
reader.readAsText(FinalFile);
} else {
console.log('not yet');
}
}
};
// sending XMLHttpRequest
xhr.send();
});
*edit I also updated the append function to ensure that the files are in the correct order

Using EXIF and BinaryFile get an error

I'm trying to draw photo with correct orientation in canvas after capture photo by using input[type='file'] in mobile web browser for that I'm using:
fileReader.onloadend = function() {
var exif = EXIF.readFromBinaryFile(new BinaryFile(this.result));
switch(exif.Orientation){
case 8:
ctx.rotate(90*Math.PI/180);
break;
case 3:
ctx.rotate(180*Math.PI/180);
break;
case 6:
ctx.rotate(-90*Math.PI/180);
break;
}
};
But I get: TypeError: First argument to DataView constructor must be an ArrayBuffer?
How can I get this array buffer?
I'm using EXIF.js and BinaryFile.js
You need to convert the base64 string to an ArrayBuffer for ExifJs:
function base64ToArrayBuffer (base64) {
base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
var binaryString = atob(base64);
var len = binaryString.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
You don't need BinaryFile:
var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(this.result));
This assumes you are using FileReader with readAsDataURL to get this.result.
A better approach would be to read the file as an array buffer to begin with and not convert it to base64 and then back again using FileReader.readAsArrayBuffer(). Something along the lines of this (pseudocode):
// `file` = files[0] from input change event
function getFileArrayBuffer(file) {
return new Promise(function (resolve, reject) {
var reader = new FileReader();
reader.onload = function() {
resolve(new Uint8Array(reader.result));
}
reader.readAsArrayBuffer(file);
});
}
#chings228 you must pass base64 data to base64ToArrayBuffer, not blob data.
function base64ToArrayBuffer (base64) {
base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
var binaryString = atob(base64);
var len = binaryString.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
var b64 = "data:image/jpeg;base64,"+$parameters.image;
var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(b64));
alert(exif.Orientation);

Categories

Resources