Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active March 20, 2024 04:21
Show Gist options
  • Star 59 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
  • Save tanaikech/bd53b366aedef70e35a35f449c51eced to your computer and use it in GitHub Desktop.
Save tanaikech/bd53b366aedef70e35a35f449c51eced to your computer and use it in GitHub Desktop.
Upload Files to Google Drive using Javascript

Upload Files to Google Drive using Javascript

News

At October 11, 2019, I published a Javascript library to to run the resumable upload for Google Drive. When this is used, the large file can be uploaded. You can also use this js library.

Description

This is a sample script for uploading files to Google Drive using Javascript. The files are uploaded by Drive API v3. gapi.client.drive.files.create() can create an empty file on Google Drive. But it cannot directly upload files including contents. I think that this might not be able to upload files and metadata with the multipart/related, although this might be resolved by the future update. So now, as one of workarounds, I use using XMLHttpRequest.

  • This sample uses gapi.
    • Before you use this, please enable Drive API at API console and carry out the installation of gapi.
  • When this script is run, a text file including "sample text" is created to Google Drive.
  • When you use this script, please set fileContent and metadata.

In this sample script, a text file including contents is created under a folder.

Sample script :

var fileContent = 'sample text'; // As a sample, upload a text file.
var file = new Blob([fileContent], {type: 'text/plain'});
var metadata = {
    'name': 'sampleName', // Filename at Google Drive
    'mimeType': 'text/plain', // mimeType at Google Drive
    'parents': ['### folder ID ###'], // Folder ID at Google Drive
};

var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
form.append('file', file);

var xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id');
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
    console.log(xhr.response.id); // Retrieve uploaded file ID.
};
xhr.send(form);

Request body :

In this script, form is as follows. This is sent to Google Drive using the create method of Drive API.

------WebKitFormBoundaryxX0XmxgooMjdUECR
Content-Disposition: form-data; name="metadata"; filename="blob"
Content-Type: application/json

{"name":"sampleName","mimeType":"text/plain","parents":["#####"]}
------WebKitFormBoundaryxX0XmxgooMjdUECR
Content-Disposition: form-data; name="file"; filename="blob"
Content-Type: text/plain

sample text
------WebKitFormBoundaryxX0XmxgooMjdUECR--

Sample script 2

When XMLHttpRequest is modified to fetch, the script becomes as follows.

var fileContent = 'sample text'; // As a sample, upload a text file.
var file = new Blob([fileContent], {type: 'text/plain'});
var metadata = {
    'name': 'sampleName', // Filename at Google Drive
    'mimeType': 'text/plain', // mimeType at Google Drive
    'parents': ['### folder ID ###'], // Folder ID at Google Drive
};

var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
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&fields=id', {
    method: 'POST',
    headers: new Headers({ 'Authorization': 'Bearer ' + accessToken }),
    body: form,
}).then((res) => {
    return res.json();
}).then(function(val) {
    console.log(val);
});

Testing:

  • January 11, 2022: When I tested this script, no error occurs. I could confirm that A text file including sample text as the filename of sampleName can be created to the specific folder.
@prajwalqubited
Copy link

how can we upload image or docs file what should I pass in fileContent ?

@vsl-dev
Copy link

vsl-dev commented Jan 25, 2024

How we can make these files to share public?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment