Fetching a file from google drive and parsing it - javascript

I am able to fetch the contents of a zip file from google drive using javascript api. But i am not able to unzip the file. I am using JSZip (http://stuartk.com/jszip) to unzip. How do i achive this. Please help i am stuck on this from last 3 days.
gapi.client.load('drive', 'v2', function(){
var config = {
'client_id': '{!gApp.clientid__c}',
'scope': 'https://www.googleapis.com/auth/drive',
'immediate':true
};
gapi.auth.authorize(config, function() {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', fileURL);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
//reponse :unzip the file here
var zipData = xhr.responseText;
var zip = new JSZip(zipData, {base64:false});
console.log(zip.files) //get an error undefined
};
xhr.onerror = function() {
alert('error');
};
xhr.send();
});
});

Related

Getting Fetch/XMLHttpRequest API cannot load blob:url due to access control checks while making request from WKwebview

So, To download images/pdf that have blob: url in wkwebview, i injected javascript to my code.Here's the javaScript:
function(url) {
function blobToBase64String(blob, callback) {
var reader = new FileReader();
reader.onloadend = function() {
callback(this.result.split(",")[1]);
};
reader.readAsDataURL(blob);
}
if (url.startsWith("blob:")) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.responseType = "blob";
xhr.onload = function() {
if (this.status !== 200) {
return;
}
var blob = this.response;
blobToBase64String(blob, function(base64String) {
webkit.messageHandlers.downloadManager.postMessage({
url: url,
mimeType: blob.type,
size: blob.size,
base64String: base64String
});
});
};
xhr.send();
return;
}
var link = document.createElement("a");
link.href = url;
link.dispatchEvent(new MouseEvent("click"));}
This is the error i m getting:
XMLHttpRequest cannot load blob:https://url due to access control checks.
Is there any way to allow request in wkwebview. I m not sure, where to head forward! Is there any preferences in wkwebview, that needs to be enabled?

Google Drive API browser upload PDF empty

I can upload the pdf file, but it will upload as blank/empty file. I don't know what am i missing from here.
Backend i receive the file, i also tried without converting to Base64 and still the same thing.
using (var sr = new StreamReader(file.OpenReadStream(), System.Text.Encoding.UTF8))
{
_fContent = await sr.ReadToEndAsync();
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_fContent);
_fContent = System.Convert.ToBase64String(plainTextBytes);
}
Frontend i create the request.
endpoint = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id';
method = 'POST';
_metadata = {
'name': fileName,
'mimeType': 'application/pdf',
'parents': [zzzz]
};
//blob is the data we receive in backend from _fContent variable
var file = new Blob([blob], { type: 'application/pdf' });
var accessToken = gapi.auth.getToken().access_token;
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(_metadata)], { type: 'application/json' }));
form.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open(method, endpoint);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
GapiUploadCallback(xhr.response, responseReturn);
};
xhr.send(form);
This is what i receive in google drive API, an empty/blank PDF file. Note: File size is
1 MB (1,424,457 bytes)
Using javascript FileReader was the only option i could solve this. PDF's are rendering ok on Google Drive now.
var fileUpload = $("#fileUpload").get(0);
var files = fileUpload.files;
var reader = new FileReader();
reader.onload = function () {
var dataURL = reader.result;
var file = new Blob([dataURL], { type: 'application/pdf' });
var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(_metadata)], { type: 'application/json' }));
form.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open(method, endpoint);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
GapiUploadCallback(xhr.response, responseReturn);
};
xhr.send(form);
};
reader.readAsArrayBuffer(files[0]);

JavaScript; Getting the content of the file into array chunks

I am working on the Google Drive API to get a document from the google drive, and then I’m trying to get the document’s contents into chunks of blocks so I can encrypt block-by-block. Can you help me figure out a way of achieving that? This is what I have tried.
function getDocumentContents() {
var accessToken = user.getAuthResponse().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.googleapis.com/drive/v3/files/' + fileId
+ '?alt=media');
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
modelContent = xhr.responseText;
extractKey(xhr.responseText);
};
xhr.onerror = function() {
alert('error');
};
xhr.send();
var chunkSize=512*512;
var fileSize=file.size;
var chunks=Math.ceil(xhr.size/chunkSize,chunkSize);
var chunk=0;
console.log('chunks...',chunks);
while( chunk <= chunks)
var offset=chunk*chunkSize;
console.log('current chunk..', chunk);
chunk.send();
console.log('offset',offset);
console.log(xhr.slice(offset,offset+chunkSize));
}
Thanks

JS FileSaver non interactive

I have an array of file to save by using a loop and i generate the name of each file. I want to save file directly (in non interactive way) without asking me to confirm. How can i do ?
Here is my code for saving file
var url = img.src.replace(/^data:image\/[^;]/, 'data:application/octet-stream');
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; //Set the response type to blob so xhr.response returns a blob
xhr.open('GET', url , true);
xhr.onreadystatechange = function () {
if (xhr.readyState == xhr.DONE) {
var filesaver = require('file-saver');
filesaver.saveAs(xhr.response, nameFile); // nameFile the name of file to be saved
}
};
xhr.send(); //Request is sent
Finally, i find a solution, instead of saving file, i write it by creating a new one.
for (var i = 0; i < tabForm.length; i++) {
var imgData = $('#affichageqr')[0].childNodes[1].childNodes[0].src;
var data = imgData.replace(/^data:image\/\w+;base64,/, '');
fs.writeFile(qrcode.getNomQRCode()+'.jpeg', data, {encoding: 'base64'}, function(err){
if (err) {
console.log('err', err);
}
console.log('success');
});
}

How to use download files from google drive in javascript?

Where should i paste this function. I have tried millions of times but failed. Can anyone give me the full html page with this function. I have replaced with insert() on quickstart but failed. Please help me.Give me full html page.
function downloadFile(file, callback) {
if (file.downloadUrl) {
var accessToken = gapi.auth.getToken().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', file.downloadUrl);
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.onload = function() {
callback(xhr.responseText);
};
xhr.onerror = function() {
callback(null);
};
xhr.send();
} else {
callback(null);
}
}

Categories