Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
});
@jamsshhayd

This comment has been minimized.

Copy link

@jamsshhayd jamsshhayd commented Oct 5, 2018

So, How the authorization of google account will work?

@spinualexandru

This comment has been minimized.

Copy link

@spinualexandru spinualexandru commented Oct 19, 2018

So, How the authorization of google account will work?

Seems like authentication is done using the standard access token via gapi: Google API Reference

@gutierrezjeralds

This comment has been minimized.

Copy link

@gutierrezjeralds gutierrezjeralds commented Nov 16, 2018

Hello, how about the percentage of the upload progress?

@gsborisgithub

This comment has been minimized.

Copy link

@gsborisgithub gsborisgithub commented Dec 20, 2018

'parents': ['### folder ID ###']
do you need to provide it?

@dmarshall83

This comment has been minimized.

Copy link

@dmarshall83 dmarshall83 commented Jan 10, 2019

any idea how to get this to work with resumeable uploads

@SamuelMuloki

This comment has been minimized.

Copy link

@SamuelMuloki SamuelMuloki commented Mar 22, 2019

This worked great for me thanks.

@tanaikech

This comment has been minimized.

Copy link
Owner Author

@tanaikech tanaikech commented Apr 7, 2019

You can see a sample about the resumable upload at https://github.com/tanaikech/Resumable_Upload_For_WebApps

@tanaikech

This comment has been minimized.

Copy link
Owner Author

@tanaikech tanaikech commented Apr 7, 2019

If you don't want to put the file to the specific folder, you can remove 'parents': ['### folder ID ###'],.

@tyzero

This comment has been minimized.

Copy link

@tyzero tyzero commented Aug 9, 2019

Cool Man!

@tanaikech

This comment has been minimized.

Copy link
Owner Author

@tanaikech tanaikech commented Aug 10, 2019

Thank you!

@trantronghien

This comment has been minimized.

Copy link

@trantronghien trantronghien commented Apr 3, 2020

Hi tannaukech, how to upload a file from input element to google drive? I tried to use javascript object file to upload, but i got a problem. I attach a picture about my problem below. I'm looking forward to hear from you soon. Thank you.
image

@sarangnx

This comment has been minimized.

Copy link

@sarangnx sarangnx commented Apr 7, 2020

Seems like you are converting the form object to string, I guess.

@itsmhuang

This comment has been minimized.

Copy link

@itsmhuang itsmhuang commented Apr 22, 2020

Was able to get it to work but what do I do with the file ID that's returned? It doesn't match any part of the URL for the created file when I go to google drive and open it. I assume I have to call another endpoint to get an actual URL.

@itsmhuang

This comment has been minimized.

Copy link

@itsmhuang itsmhuang commented Apr 22, 2020

figured it out for anyone interested. Add to the endpoint the fields param with value webViewLink. This tutorial has fields=id, but use fields=webViewLink instead or add to it and whatever other properties you're interested in the response. E.g. 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=webViewLink'

@RicardoSimoesRKS

This comment has been minimized.

Copy link

@RicardoSimoesRKS RicardoSimoesRKS commented Sep 21, 2020

I tried out this code but I'm getting a
Exception: Unexpected error while getting the method or property newBlob on object Utilities. error.
I thought this script didn't use any google script, and I couldn't find anywhere a place to set my own script.
Its just giving me this one: https://script.google.com/macros/s/AKfycbwhJjevFmbIZ_FQztQKHV9s9yXwPy-v7WBlOuz4W8ejN7gNgVs/exec

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.