javascript - 如何使用 google drive api 将文件上传到 google drive?
问题描述
我按照文档(https://developers.google.com/drive/api/v3/manage-uploads#http---single-request)做了,但它不起作用:
var fileMetadata = {
name: e.target.files[j].name,
parents: this.currentDirectoryId ? [this.currentDirectoryId] : []
}
var media = {
mimeType: e.target.files[j].type,
body: e.target.files[j]
}
window.gapi.client.drive.files.create({
resource: fileMetadata,
media: media,
fields: 'id, name, mimeType, createdTime'
}).then(res => console.log(res))
文件已创建,但为空并命名为“无标题”,mimeType 为“application/octet-stream”
解决方案
问题和解决方法:
当我测试
gapi.client.drive.files.create
时,似乎这种方法虽然可以使用元数据创建新文件,但无法包含文件内容。所以在这个答案中,为了通过包含文件元数据来上传文件,我想建议multipart/form-data
使用fetch
Javascript 上传文件。在这种情况下,访问令牌由 检索gapi.auth.getToken().access_token
。不幸的是,从您的脚本中,我无法理解
e.target
. 因此,在这个示例脚本中,我想提出用于上传文件的示例脚本,该文件是从输入标签中检索到的,带有元数据。
示例脚本:
HTML 方面:
<input type="file" id="files" name="file">
Javascript方面:
const files = document.getElementById("files").files;
const file = files[0];
const fr = new FileReader();
fr.readAsArrayBuffer(file);
fr.onload = (f) => {
const fileMetadata = {
name: file.name,
parents: this.currentDirectoryId ? [this.currentDirectoryId] : [] // This is from your script.
}
const form = new FormData();
form.append('metadata', new Blob([JSON.stringify(fileMetadata)], {type: 'application/json'}));
form.append('file', new Blob([new Uint8Array(f.target.result)], {type: file.type}));
fetch('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart', {
method: 'POST',
headers: new Headers({'Authorization': 'Bearer ' + gapi.auth.getToken().access_token}),
body: form
}).then(res => res.json()).then(res => console.log(res));
};
- 在此脚本中,从
input
标签检索到的文件以multipart/form-data
.
笔记:
- 在此脚本中,它假设您的授权脚本可用于将文件上传到 Google Drive。请注意这一点。
- 在此答案中,作为示例脚本,该文件使用
uploadType=multipart
. 在这种情况下,最大文件大小为 5 MB。请注意这一点。当您要上传大尺寸文件时,请勾选可续传。参考
参考:
推荐阅读
- android - E/FirebaseInstanceId:令牌检索失败:SERVICE_NOT_AVAILABLE
- checkbox - 在递归剔除中获取检查的属性
- c++ - 如何使头文件可以通过库名称包含?
- linux-kernel - Linux 是否在 mmap() 之后立即为进程分配内存?
- java - 对象是否应该与主 Activity 交互?
- python - 从 JSON 文件中提取名称
- python-3.x - 使用 Python 3.6 覆盖 Image Exif 中的 GPS 坐标
- scala - Swagger 工件在外部库中,但 IntellIJ 看不到
- teradata - TPT 脚本在运行时加载另一个文件
- react-admin - 如何在反应管理员中获得自定义操作的响应