简体   繁体   中英

JavaScript read all text from txt file on Google drive or Dropbox

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.

Here is a javascript function to download text file from Google Drive . Using fetch API.

  function get_doc(id){
    const url = 'https://www.googleapis.com/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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM