Skip to content

Instantly share code, notes, and snippets.

@tuannrio
Forked from tanaikech/submit.md
Created September 25, 2020 06:23
Show Gist options
  • Save tuannrio/de4f4c178b4ed64246bb0e48ef50117a to your computer and use it in GitHub Desktop.
Save tuannrio/de4f4c178b4ed64246bb0e48ef50117a to your computer and use it in GitHub Desktop.
Simple Script of Resumable Upload with Google Drive API for Node.js

Simple Script of Resumable Upload with Google Drive API for Node.js

This is a simple sample script for achieving the resumable upload to Google Drive using Node.js. In order to achieve the resumable upload, at first, it is required to retrieve the location, which is the endpoint of upload. The location is included in the response headers. After the location was retrieved, the file can be uploaded to the location URL.

In this sample, a PNG file is uploaded with the resumable upload using a single chunk.

Sample script

Before you use this, please set the variables.

const fs = require("fs");
const request = require("request");

const accessToken = "###"; // Please set the access token.
const filename = "./sample.png"; // Please set the filename with the path.

const fileSize = fs.statSync(filename).size;

// 1. Retrieve session for resumable upload.
request(
  {
    method: "POST",
    url:
      "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
    headers: {
      Authorization: `Bearer ${accessToken}`,
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ name: "sample.png", mimeType: "image/png" })
  },
  (err, res) => {
    if (err) {
      console.log(err);
      return;
    }

    // 2. Upload the file.
    request(
      {
        method: "PUT",
        url: res.headers.location,
        headers: { "Content-Range": `bytes 0-${fileSize - 1}/${fileSize}` },
        body: fs.readFileSync(filename)
      },
      (err, res, body) => {
        if (err) {
          console.log(err);
          return;
        }
        console.log(body);
      }
    );
  }
);

Reference

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