javascriptreactjsgoogle-drive-apigoogle-drive-picker

how to retrieve text from google drive documents


I am using react-google-drive-picker to select a file from GDrive in my NextJS app. Once I have picked a file and retrieved the meta information, what is the suggested way to download or just retrieve the file content? What API is suggested to use authResponse to authenticate?

I am using:

useEffect(() => {
 // do anything with the selected/uploaded files
 if (data) {
    var file = data.docs[0]
    var xhr = new XMLHttpRequest();
    xhr.open('GET', file['url']);
    xhr.setRequestHeader('Authorization', 'Bearer ' + authResponse['access_token']);
    xhr.setRequestHeader('Content-Type', 'application/vnd.google-apps.document');
    xhr.onload = function () {
        var content = xhr.responseText
        console.log(content)
    };
    xhr.onerror = function () {
        console.log("ERROR LOADING THE FILE")
    };
    xhr.send(JSON.stringify({"alt" : "media"}));
 }
}, [data])

but the text of the document is not present in the response...


Solution

  • following the suggestion by @Gonzalo-Matheu, here's a way to obtain the text after picking a file with react-google-drive-picker in nextjs:

    var file = data.docs[0]
    var xhr = new XMLHttpRequest();
    var url = 'https://www.googleapis.com/drive/v3/files/' + file['id'] + '/export?mimeType=text%2Fplain&key=' + process.env.NEXT_PUBLIC_GOOGLE_API_KEY
    xhr.open('GET', URL);
    xhr.setRequestHeader('Authorization', 'Bearer ' + authResponse['access_token']);
    xhr.onload = function () {
     var value = xhr.responseText
     // do what you need with file content
     console.log(value)
    };
    xhr.onerror = function () {
      console.log("ERROR LOADING THE FILE")
    };
    xhr.send();