1

After downloading an image from google drive using the google drive API, In response what i get is a PNG Chunks text of my downloaded image. But, I could't get the png file from that text. How can i convert it to a PNG by javaScript?

    // google drive download file function
    function downloadFile(Url, callback) {
      console.log("download url-->",file.downloadUrl)
        // if (file.downloadUrl) 
        if (Url) 
        {
          var accessToken = gapi.auth.getToken().access_token;
          var xhr = new XMLHttpRequest();
          // xhr.open('GET', file.downloadUrl);
          xhr.open('GET',Url);
          xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
          xhr.onload = function() {
            callback(xhr.responseText);
          };
          xhr.onerror = function() {
            callback(null);
          };
          xhr.send();
        } else {
          callback(null);
        }
    }

 downloadFile("https://www.googleapis.com/drive/v2/files/id?alt=media&source=downloadUrl", 
  function(resp){
        console.log("resp",resp)
  })

Here is the chunk text file I get ere is the chunk text file I get

BenEgan1991
  • 637
  • 1
  • 9
  • 15
  • You're getting `xhr.responseText` which is trying to handle it as unicode text - try getting `xhr.response` instead – Rycochet Aug 19 '21 at 05:58
  • I recommend moving to google drive v3 and consulting the documentation to see how the file response can be downloaded directly from file.get rather than using the download link https://developers.google.com/drive/api/v3/manage-downloads – Linda Lawton - DaImTo Aug 19 '21 at 10:03
  • Just like mentioned above, have you tried using the v3 of Drive API for this? – ale13 Aug 19 '21 at 14:21

1 Answers1

0

You should work with xhr.response, because xhr.responseText returns text, as you found out already.

Also, you must define xhr.type, otherwise xhr.response will return text as well.

You could set xhr.type="arraybuffer" to get the file content in an array buffer, or xhr.type="blob", if you would like to get a blob. With a blob and FileSaver.js (https://github.com/eligrey/FileSaver.js/) you could download the file, for example.

Mario Varchmin
  • 3,704
  • 4
  • 18
  • 33