首页 > 解决方案 > 如何使用 Google Drive api V3 将图像下载到浏览器客户端?

问题描述

目标是让应用程序的用户通过浏览器从 Google Drive 下载图像 (jpg)。

使用更下方的代码,我确实设法让浏览器提示“另存为”对话框,并且用户将文件保存到磁盘,但是尝试打开 jpg 文件会导致错误:

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

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

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

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))
}

标签: javascriptgoogle-drive-api

解决方案


我遇到了与您的情况相同的问题。那个时候,一开始我把返回值转换成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'}));

推荐阅读