Google Drive API and file uploads from the browser


I’m trying to upload a file with the Google Drive api, and I have the metadata correct, and I want to ensure that the actual file contents make it there. I have a simple page setup that looks like this:

<div id="upload">
  <h6>File Upload Operations</h6>
  <input type="file" placeholder='file' name='fileToUpload'>
  <button id='uploadFile'>Upload File</button>

and I have a the javascript setup where the user is prompted to sign in first, and then they can upload a file. Here’s the code: (currently only uploads the file metadata….)

let uploadButton = document.getElementById('uploadFile');
uploadButton.onclick = uploadFile;
const uploadFile = () => {
    let ftu = document.getElementsByName('fileToUpload')[0].files[0];
        'content-type': 'application/json;charset=utf-8',
        uploadType: 'multipart',
        mimeType: ftu.type,
        fields: 'id, name, kind'
    }).then(response => {
        console.log(`File: ${} with MimeType of: ${ftu.type}`);
        //Need code to upload the file contents......

First, I’m more familiar with the back end, so getting the file in bits from the <input type='file'> tag is a bit nebulous for me. On the bright side, the metadata is there. How can I get the file contents up to the api?


So According to some resources I’ve found in my three day search to get this going, the file simply cannot be uploaded via the gapi client. It must be uploaded through a true REST HTTP call. So let’s use fetch!

const uploadFile = () => {
    //initialize file data from the dom
    let ftu = document.getElementsByName('fileToUpload')[0].files[0];
    let file = new Blob([ftu]); 
    //this is to ensure the file is in a format that can be understood by the API{
        'content-type': 'application/json',
        uploadType: 'multipart',
        mimeType: ftu.type,
        fields: 'id, name, kind, size'
    }).then(apiResponse => {
        fetch(`${}`, {
         method: 'PATCH',
         headers: new Headers({
             'Authorization': `Bearer ${gapi.client.getToken().access_token}`,
              'Content-Type': ftu.type
         body: file
       }).then(res => console.log(res));


The Authorization Header is assigned from calling the gapi.client.getToken().access_token function, and basically this takes the empty object from the response on the gapi call and calls the fetch api to upload the actual bits of the file!

Answered By – Chris Rutherford

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published