javascript - 如何使用 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))
}
解决方案
我遇到了与您的情况相同的问题。那个时候,一开始我把返回值转换成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'}));
推荐阅读
- winapi - 如何在 win32 中使用 SetTextColor 更改文本 SetDlgItemText 的颜色?
- math - 我将使用“光线投射器”选择“对象”之一进行放大
- python - MNIST图像数据上的EM算法python
- java - 如何在不发送实体的完整 json 的情况下更新对象
- azure - Azure 事件网格出口限制
- python - 基于其他两个类/表自动填充由 sqlalchemy 类定义的表
- ios - UILabel 没有在 UIStackView 中使用 addArrangedView 呈现;使用 addSubView 渲染
- abap - 不存在日志数据。查看集群的问题
- javascript - 在 setState React 中使用参数作为对象的名称
- flutter - 在颤动中获取带有号码和姓名的联系人列表