1

I'm trying to download users images in the browser using the google drive rest api, but I can't seem to get to the actual image data. I'm able to successfully call the files endpoint, but I don't know what to do with the response.

my fetch request:

fetch(`https://www.googleapis.com/drive/v3/files/${fileId}?key=${driveInfo.key}`, settings)
    .then(res => {
      return res.json();
    })
    .then(json => {
      console.log("drive json", json);
    });

which outputs:

drive json
{
kind: "drive#file"
id: "1qXXBU6oIxs2Y4PZskA-kj6ljMjTfGKjf"
name: "Screenshot_20180919-160538.png"
mimeType: "image/png"
}

I've also noticed that response.body is a ReadableStream<Uint8Array> which is great, as I ultimately need a uint8 array, but it looks like the uint8 array represents the above meta data rather than the actual image data.

Am I even going about this the right way, or am I way off in this attempt to download images in the client?

Jesse Sliter
  • 233
  • 1
  • 4
  • 15

1 Answers1

5
  • You want to download the file from Google Drive with the API key using fetch of Javascript.
  • The file is publicly shared.

If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.

Modification points:

  • In order to download the file as the binary data, please add alt=media to the query parameter.
    • When alt=media is not used, the file metadata is returned.

Modified script:

fetch(`https://www.googleapis.com/drive/v3/files/${fileId}?key=${driveInfo.key}&alt=media`, settings)
  .then(res => {
    return res.arrayBuffer();
  })
  .then(data => {
     console.log(data);
  });

Note:

  • When the file is not publicly shared, the file cannot be downloaded by the API key. Please be careful this.
  • In above script, the data is retrieved as arrayBuffer.
    • If you want to retrieve the data as the blob, please modify return res.arrayBuffer(); to return res.blob();

References:

If I misunderstood your question and this was not the result you want, I apologize.

Tanaike
  • 181,128
  • 11
  • 97
  • 165
  • 1
    The alt=media parameter did the trick, many thanks! I'll also note that the images I'm testing on are in fact not public, but I pass an authorization token as part of the fetch settings object in my code. This seems to work fine – Jesse Sliter Jan 16 '20 at 03:14
  • 1
    @Jesse Sliter Thank you for replying. I'm glad your issue was resolved. – Tanaike Jan 16 '20 at 03:19