【问题标题】:Google drive & vuejs3 - upload file to a specific folderGoogle drive & vuejs3 - 将文件上传到特定文件夹
【发布时间】:2023-01-16 20:01:26
【问题描述】:

这是我将文件上传到谷歌驱动器的功能:

    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)。 我在这里做错了什么?

我已经尝试了一些功能,这是唯一一个将文件上传到谷歌驱动器的功能。

【问题讨论】:

  • 您是否尝试过使用console.log(this.currentFolder.folderId) 登录并验证此文件夹 ID 存在于谷歌驱动器中?我认为它可能是空的或无效的。
  • 我验证了它,它存在。

标签: javascript vue.js web google-drive-api frontend


【解决方案1】:

parents 是一个列表参数,因此您应该在表单字段中作为一个提供。

像这样:

formData.append("parents[]", this.currentFolder.folderId)

【讨论】:

  • 试过了还是不行,它上传了文件但没有上传到特定的文件夹
  • 文档明确指出:developers.google.com/drive/api/v3/reference/files/createparents[]:“如果未指定为创建请求的一部分,文件将直接放置在用户的我的云端硬盘文件夹中。”所以出于某种原因它仍然没有正确传递父文件夹。尝试在浏览器的网络检查器中检查您的帖子数据。它应该在有效负载中包含parents[]: bwafuejjweaklfjweah3294y23894e(文件夹哈希)
【解决方案2】:

在你的脚本中,如何进行以下修改?

修改脚本:

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] 的文件将与 { name: files[0].name, parents: [this.currentFolder.folderId] } 的文件元数据一起上传到 Google 云端硬盘。

  • multipart/form-datanew FormData()运行请求时,不需要设置请求头的内容类型。包括边界在内的内容类型是自动创建的。

  • 为了设置文件元数据,我使用了formData.append('metadata', new Blob([JSON.stringify({ name: files[0].name, parents: [this.currentFolder.folderId] })], { type: 'application/json' }));

笔记:

  • 在此修改中,假设 files[0] 是有效的文件对象,并且您的访问令牌可用于使用 Drive API 将文件上传到 Google Drive。请注意这一点。

参考:

【讨论】: