I would like to use JavaScript to read the entire content of a txt file on Google Drive or Dropbox into a string variable. I've seen similar questions, but I would like to have it done purely with JavaScript. I have already tried some ways, but I keep getting "XMLHttpRequest cannot load ... no 'access-control-allow-origin' " and "Failed to execute 'send' " errors. I would also like to do this without any external APIs or installations.
I would like to use JavaScript to read the entire content of a txt file on Google Drive or Dropbox into a string variable. I've seen similar questions, but I would like to have it done purely with JavaScript. I have already tried some ways, but I keep getting "XMLHttpRequest cannot load ... no 'access-control-allow-origin' " and "Failed to execute 'send' " errors. I would also like to do this without any external APIs or installations.
Share Improve this question asked Jul 18, 2016 at 22:44 Daniel WilliamsDaniel Williams 6652 gold badges8 silver badges15 bronze badges2 Answers
Reset to default 3Here is a javascript function to download text file from Google Drive. Using fetch API.
function get_doc(id){
const url = 'https://www.googleapis./drive/v3/files/'+id+'?alt=media'
if(self.fetch){
var setHeaders = new Headers();
setHeaders.append('Authorization', 'Bearer ' + authToken.access_token);
setHeaders.append('Content-Type', mime);
var setOptions = {
method: 'GET',
headers: setHeaders
};
fetch(url,setOptions)
.then(response => { if(response.ok){
var reader = response.body.getReader();
var decoder = new TextDecoder();
reader.read().then(function(result){
var data = {}
data = decoder.decode(result.value, {stream: !result.done});
console.log(data);
});
}
else{
console.log("Response wast not ok");
}
}) .catch(error => {
console.log("There is an error " + error.message);
});
}
}
Refer here in case of Google Docs file.
s007
answer works pretty ok but I have no idea why it doesn't return all texts in the file (some got trimmed). Below I use the files.get
function from google drive javascript api. So this works after you authenticate.
this.readFile = function(fileId,callback){
var request = gapi.client.drive.files.get({
fileId: fileId,
alt: 'media'
})
request.then(function(response){
console.log(response); //response.body has the text content of the file
if (typeof callback === "function") callback(response.body);
},function(error){
console.error(error)
})
return request; //for batch request
}