如何将带有 Google Drive api V3 的图像下载到浏览器客户端?

How do you download an image with Google Drive api V3 to a browser client?

objective 是让应用程序的用户通过浏览器从 Google 驱动器下载图像 (jpg)。

使用下面的代码,我设法让浏览器提示 'Save as' 对话框并且用户将文件保存到磁盘,但是尝试打开 jpg 文件会导致错误:

“解释 JPEG 图像文件时出错(不是 jpeg 文件:以 0xc3 0xbf 开头)”

请问下面的代码有问题吗?

或者可能是 'response.body' 需要解压缩,因为响应具有“内容编码:gzip”?

const downloadFile = (fileId) => {
        gapi.client.drive.files.get({
            fileId: fileId,
            alt: "media",
          })
            .then((response) => {

                const objectUrl = URL.createObjectURL(new Blob([response.body] , {type:'image/jpeg'}))

                // 'ref' is 'userRef' React hook pointing to an anchor element:
                ref.current.href = objectUrl
                ref.current.download = 'my-image.jpg'
                ref.current.click()
            })
            .catch((err) => console.log(err))
}

我遇到了与你的情况相同的问题。当时,一开始我是把返回值转成Unit8Array再转成blob。那么,在你的脚本中,下面的修改怎么样?

发件人:

const objectUrl = URL.createObjectURL(new Blob([response.body] , {type:'image/jpeg'}))

收件人:

const objectUrl = URL.createObjectURL(new Blob([new Uint8Array(response.body.length).map((_, i) => response.body.charCodeAt(i))], {type: 'image/jpeg'}));