javascriptvue.jsgoogle-drive-api

How to upload a file to a specific folder?


This is my function to upload the file to google drive:

    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)
        })
    },

the file is uploading to the general google drive and not to the specific folder (this.currentFolder.folderId). What am I doing wrong here?

I tried some functions already and this is the only one that uploads file to the google drive.


Solution

  • In your script, how about the following modification?

    Modified script:

    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)
        })
    },
    

    Note:

    References: