简体   繁体   English

使用 REST api 从 Google Drive 下载图像

[英]Download images from Google Drive using the REST api

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.我正在尝试使用 google drive rest api 在浏览器中下载用户图像,但我似乎无法获得实际的图像数据。 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.我还注意到response.body是一个ReadableStream<Uint8Array> ,这很棒,因为我最终需要一个 uint8 数组,但看起来 uint8 数组代表上述元数据而不是实际的图像数据。

Am I even going about this the right way, or am I way off in this attempt to download images in the client?我什至以正确的方式解决这个问题,还是我在尝试在客户端下载图像时偏离了方向?

  • You want to download the file from Google Drive with the API key using fetch of Javascript.您想使用 Javascript fetch使用 API 密钥从 Google Drive 下载文件。
  • 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.要将文件下载为二进制数据,请在查询参数中添加alt=media
    • When alt=media is not used, the file metadata is returned.当不使用alt=media ,返回文件元数据。

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.当文件未公开共享时,无法通过 API 密钥下载文件。 Please be careful this.请注意这一点。
  • In above script, the data is retrieved as arrayBuffer.在上面的脚本中,数据被检索为 arrayBuffer。
    • If you want to retrieve the data as the blob, please modify return res.arrayBuffer();如果要检索数据为blob,请修改return res.arrayBuffer(); to return res.blob(); return res.blob();

References:参考:

If I misunderstood your question and this was not the result you want, I apologize.如果我误解了您的问题并且这不是您想要的结果,我深表歉意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM