avatarAnshu Sharma

Summary

The web content provides a step-by-step guide on how to upload a file to Google Drive using Node.js, with detailed code examples and explanations.

Abstract

The article explains the process of uploading a file to Google Drive via a Node.js application. It outlines the use of Postman to send a file to an API endpoint, which then uses the Multer package to handle file uploads and the googleapis package to authenticate and interact with Google Drive. The guide includes setting up a service account for authentication, configuring a Google Drive folder to store the files, and writing the necessary Node.js code to upload the file and retrieve its ID. The author provides code snippets for the index.js, upload-router.js, and upload-controller.js files, as well as the structure of the package.json file and the service account JSON. The article concludes with a request for readers to acknowledge the tutorial by clapping for the article if it proves helpful.

Opinions

  • The author, Anshu, believes that the provided instructions and code examples will be beneficial to the reader, as indicated by the request for feedback through clapping for the article.
  • The use of Multer for handling file uploads and the googleapis package for Google Drive interaction is recommended as a practical solution for the task.
  • The author suggests using a temporary directory for storing files during the upload process, but also notes that the reader can choose any directory they prefer.
  • The article implies that the service account should be given editor access to the specific Google Drive folder where files will be uploaded, indicating a preference for this level of access control.
  • The inclusion of error handling in the upload-controller.js file suggests that the author values robust code practices.

How to upload a file to Google Drive and get the file ID using Node.js

Explaining it using an API example. The API will get the file from Postman and then upload it to Google Drive using the Multer npm package. Then using the googleapis npm package authenticate to drive and get the file ID.

1. First, you have to use Postman or any other tool to send the request to the API. I had given my API name and key with my choice, you can give in your choice.

2. index.js file will look like this

const express = require("express");
const uploadRouter = require("./routes/upload-router");
const app = express();
app.use("/", uploadRouter);
app.listen(8080);

3. upload-router.js file will look like this

const express = require("express");
const multer = require("multer");
const os = require("os");
const router = express.Router();
const { getFileDetails } = require("../controllers/upload-controller");
const storage = multer.diskStorage({ destination: os.tmpdir(), filename: (req, file, callback) => callback(null, `${file.originalname}`) });
const upload = multer({ storage: storage });
router.post("/uploadToDrive", upload.single("drive_file"), getFileDetails);
module.exports = router;

Here I used a temporary directory for storing the file you can use any directory of your choice and the file name is set with the original name which you can modify in the storage object according to your requirement.

4. Create a folder where you want to store the files. Move inside the folder and from the URL get the folder id.

Also at the same time, move inside the folder -> tap on share -> In add people or groups add your service account id like “[email protected]” with the editor option -> click send to authenticate the service account to read and write in the specific folder.

5. Service account “some-service-account.json” must be present in the root directory. It something look like this

{
  "type": "service_account",
  "project_id": "projectname",
  "private_key_id": "randomalphanumericid",
  "private_key": "-----BEGIN PRIVATE KEY-----\nsomethingbigalphanumerickey\n-----END PRIVATE KEY-----\n",
  "client_email": "[email protected]",
  "client_id": "somerandomnumber",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/[email protected]"
}

6. upload-controller.js will look like this

const { google } = require("googleapis");
const path = require("path");
const fs = require("fs");
const KEY_FILE_PATH = path.join("some-service-account.json");
const SCOPES = ["https://www.googleapis.com/auth/drive"];
const auth = new google.auth.GoogleAuth({
    keyFile: KEY_FILE_PATH,
    scopes: SCOPES,
})
exports.getFileDetails = async (req, res) => {
    try {
        const { file } = req;
        const { data } = await google.drive({ version: "v3", auth: auth }).files
            .create({
                media: {
                    mimeType: file.mimeType,
                    body: fs.createReadStream(file.path)
                },
                requestBody: {
                    name: file.originalname,
                    parents: ["1kpWF08T-CrWnApQmEj22wRliOpjqV3CJ"]   //folder id in which file should be uploaded
                },
                fields: "id,name"
            })
        console.log(`File uploaded successfully -> ${JSON.stringify(data)}`);
        res.json({ status: 1, message: "success", file_id: data.id, file_name: data.name });
    } catch (error) {
        console.log(error);
        res.json({ status: -1, message: "failure", err: error.message });
    }
}

7. Directory structure is

8. package.json will look like

{
  "name": "drive-upload",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.18.2",
    "googleapis": "^118.0.0",
    "multer": "^1.4.5-lts.1"
  }
}

Hope it will work for you. If it worked then please clap for the article.

Thank You. Anshu

Nodejs
Google Drive
File Upload
Node Js Development
Google Cloud Platform
Recommended from ReadMedium