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

javascript google-drive-api xmlhttprequest text-files dropbox

3736 просмотра

2 ответа

357 Репутация автора

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.

Автор: Daniel Williams Источник Размещён: 18.07.2016 10:44

Ответы (2)


4 плюса

530 Репутация автора

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 Размещён: 20.07.2016 06:07

2 плюса

1223 Репутация автора

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
}
Автор: phuwin Размещён: 17.04.2018 10:53
Вопросы из категории :
32x32