[英]Google drive & vuejs3 - upload file to a specific folder
这是我的 function 将文件上传到谷歌驱动器:
async processFiles(files) {
const formData = new FormData()
formData.append("file", files[0])
formData.append("name", files[0].name)
formData.append("parents", this.currentFolder.folderId)
axios
.post("https://www.googleapis.com/upload/drive/v3/files", formData, {
headers: {
Authorization: `Bearer ${this.accessToken}`,
"Content-Type": "multipart/form-data",
},
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})
},
该文件正在上传到一般的谷歌驱动器,而不是特定的文件夹(this.currentFolder.folderId)。 我在这里做错了什么?
我已经尝试了一些功能,这是唯一一个将文件上传到谷歌驱动器的功能。
在你的脚本中,下面的修改怎么样?
async processFiles(files) {
const formData = new FormData();
formData.append("file", files[0]);
formData.append('metadata', new Blob([JSON.stringify({ name: files[0].name, parents: [this.currentFolder.folderId] })], { type: 'application/json' }));
axios
.post("https://www.googleapis.com/upload/drive/v3/files", formData, {
headers: { Authorization: `Bearer ${this.accessToken}` },
})
.then((response) => {
console.log(response.data)
})
.catch((error) => {
console.log(error)
})
},
运行此脚本时, files[0]
的文件将上传到 Google 云端硬盘,文件元数据为{ name: files[0].name, parents: [this.currentFolder.folderId] }
。
当multipart/form-data
使用new FormData()
运行请求时,不需要设置请求的内容类型 header。包含边界的内容类型是自动创建的。
为了设置文件元数据,我使用formData.append('metadata', new Blob([JSON.stringify({ name: files[0].name, parents: [this.currentFolder.folderId] })], { type: 'application/json' }));
.
files[0]
是有效文件 object,您的访问令牌可用于使用 Drive API 将文件上传到 Google Drive。请注意这一点。 parents
是一个列表参数,因此您应该在表单字段中提供一个。
像这样:
formData.append("parents[]", this.currentFolder.folderId)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.