【问题标题】:How do you download an image with Google Drive api V3 to a browser client?如何使用 Google Drive api V3 将图像下载到浏览器客户端?
【发布时间】:2021-06-09 07:49:38
【问题描述】:

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

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

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

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

或者是因为响应有“content-encoding: 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))
}

【问题讨论】:

    标签: javascript google-drive-api


    【解决方案1】:

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

    【讨论】:

    • @salis010 欢迎。谢谢你让我知道。我很高兴你的问题得到了解决。如果您的问题得到解决,请按接受按钮。与您有相同问题的其他人也可以将您的问题作为可以解决的问题。我认为您的问题和解决方案将对他们有用。如果找不到按钮,请随时告诉我。 stackoverflow.com/help/accepted-answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 2012-05-05
    相关资源
    最近更新 更多