0

I have an issue when trying to download a pdf file from Google Drive via the File Picker. My code works as expected with images and videos, but not pdf files. When downloading an image through the API https://www.googleapis.com/drive/v3/files/' + file.id + '?alt=media'; i get the following response:

name: "Social-Facebook-Post-Cool-Down.png"
lastModified: 1578397749873
lastModifiedDate: Tue Jan 07 2020 12:49:09 GMT+0100 (Central European Standard Time) {}
webkitRelativePath: ""
size: 317
type: ""
url: "blob:https://localhost:8080/647e4d15-d090-4c0f-aa3e-bd7481f11043"

But when calling the same url with a pdf file id, I don't the get url property and thereby not the file content. So when opening the downloaded pdf file, it is just empty/blank. What am I missing here?

This is my code for downloading the file content:

for (let file of files) {
  var xhr = new XMLHttpRequest();
  var getUrl = 'https://www.googleapis.com/drive/v3/files/' + file.id + '?alt=media';
  xhr.open("GET", getUrl, true);
  xhr.setRequestHeader('Authorization', 'Bearer ' + this.googleDriveToken);
  xhr.responseType = 'arraybuffer';
  xhr.onload = () => {
    var bytes = new Uint8Array(xhr.response);
    let fileObj = new File([bytes], file.name);
    googleFiles.push(fileObj);
    counter++;
    if (counter == files.length) {
      this.$emit('filesAdded', googleFiles);
    }
  }
  xhr.send();
}

Thanks.

Casper Slynge
  • 344
  • 2
  • 9
  • 19
  • 1
    can you try adding a `mimeType` parameter like this : `'https://www.googleapis.com/drive/v3/files/' + file.id + '?alt=media&mimeType=application/pdf'` – Eldar Jan 07 '20 at 12:35
  • I figured out what the issue was. If I create a blob with the bytes from the file and add that to my File object, it works. `var blob = new Blob([bytes]); fileObj.url = blob;` – Casper Slynge Jan 07 '20 at 12:42

1 Answers1

0

As OP figured out, creating a blob with the bytes from the file and adding them to the File object fixed the issue:

var blob = new Blob([bytes]); 
fileObj.url = blob;

Referencing the Drive API documentation:

Blob

A file that contains text or binary content such as images, videos, and PDFs.

Community
  • 1
  • 1
Jescanellas
  • 2,555
  • 2
  • 9
  • 20