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.
CodePudding user response:
parents
is a list parameter, so you should provide as one in the form field.
Like this:
formData.append("parents[]", this.currentFolder.folderId)
CodePudding user response:
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)
})
},
When this script is run, the file of
files[0]
is uploaded to Google Drive with the file metadata of{ name: files[0].name, parents: [this.currentFolder.folderId] }
.When a request is run by
multipart/form-data
withnew FormData()
, it is not required to set the content type of the request header. The content type including the boundary is automatically created.In order to set the file metadata, I used
formData.append('metadata', new Blob([JSON.stringify({ name: files[0].name, parents: [this.currentFolder.folderId] })], { type: 'application/json' }));
.
Note:
- In this modification, it supposes that
files[0]
is the valid file object and your access token can be used for uploading the file to Google Drive using Drive API. Please be careful about this.