SexyMF
SexyMF

Reputation: 11185

Google Drive SDK Upload file from the browser via JS

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

Answers (1)

Tanaike
Tanaike

Reputation: 201623

  • You want to upload a file to the specific folder using Drive API.
  • When your script in your question is run, new folder is created.
    • Namely, you can already use Drive API.

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.

Sample script:

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

Note:

  • In this sample script, it supposes that the file is inputted by <input type="file" name='upFile'>.
  • In this sample script, the file with the size less than 5 MB can be uploaded. If you want to upload a large file more than 5 MB, please use the resumable upload. From your question, I thought that the image file might be less than 5 MB. So I proposed this script.

References:

Upvotes: 4

Related Questions