Reputation: 11185
The official documentation of v3 does not have an example of file upload (image) to drive. https://developers.google.com/drive/api/v3/manage-uploads
So I have the code to create a folder, and I need to upload file to this folder.
function createFolder(){
var parentId = '';//some parentId of a folder under which to create the new folder
var fileMetadata = {
'name' : 'New Folder',
'mimeType' : 'application/vnd.google-apps.folder',
'parents': [ROOT_FOLDER]
};
gapi.client.drive.files.create({
resource: fileMetadata,
}).then(function(response) {
switch(response.status){
case 200:
var file = response.result;
console.log('Created Folder Id: ', file);
break;
default:
console.log('Error creating the folder, '+response);
break;
}
});
}
Can you please post an example of how to upload a file to a directory in drive API v3? Thanks
Upvotes: 1
Views: 1287
Reputation: 201623
If my understanding is correct, how about this sample script? Unfortunately, in my environment, the files couldn't be uploaded using gapi.client.drive.files.create()
while a new file and new folder can be created. I thought that this might be the specification. So I used the following script as a workaround. I think that there are several solutions for your situation. So please think of this as just one of them.
let file = document.getElementsByName('upFile')[0].files[0]; // file
var metadata = {
name: file.name,
mimeType: file.type,
parents: ['### folderId ###'], // Please set folderId here.
};
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
form.append('file', file);
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) => {
return res.json();
}).then(function(val) {
console.log(val);
});
<input type="file" name='upFile'>
.Upvotes: 4