Welcome folks today in this blog post we will be uploading multiple files to folder using service account in node.js and express using google drive api in javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make a new node.js
project using the below commands as shown below
npm init -y
npm i googleapis
npm i express
npm i multer
And now you need to make the index.js
file inside the root directory and copy paste the below code
Directory Structure of App
This is the directory structure of the node.js project as shown below
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const express = require('express'); const uploadRouter = require('./router'); const app = express(); app.get('/', (_, res) => { res.sendFile(`${__dirname}/index.html`); }); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(uploadRouter); app.listen(8080, () => { console.log('Form running on port 8080'); }); |
As you can see in the above code we are importing the express
library and then we are making the express
app and then we are writing the get
route to the /
page. Here we are loading the index.html
page which we will create in the next step. And then we are using the middleware of the bodyparser inside express. And then we have the custom router also we are including the file and including it as a middleware. And then we are starting the express app at the port number of 8080.
Creating the HTML5 Form
Now we will be making the index.html
file inside the root directory and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <form> <input type="file" name="Files" required multiple /> <input type="text" name="Name" placeholder="Name" /> <input type="email" name="Email Address" placeholder="Email" required /> <input type="text" name="Country" placeholder="Country" /> <button type="submit">Submit</button> </form> </body> </html> |
And now inside the above code we are making the simple html5 form where we have four input fields. We have the input file field where we allow the users to upload multiple files and then we have the fields for name,email and country. And then we have the submit button to submit the form to upload the files to google drive.
Adding the Javascript Code
Now we will be writing the javascript code to make a simple fetch api call where we provide the post
method to call the /upload
route we will create later on inside index.js
and we will extracting all the formData and we will be sending that data to the /upload
route.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> </head> <body> <form> <input type="file" name="Files" required multiple /> <input type="text" name="Name" placeholder="Name" /> <input type="email" name="Email Address" placeholder="Email" required /> <input type="text" name="Country" placeholder="Country" /> <button type="submit">Submit</button> </form> </body> <script> const formElem = document.querySelector('form'); formElem.addEventListener('submit', async (e) => { console.log("form submitted") e.preventDefault(); await fetch('/upload', { method: 'POST', body: new FormData(formElem), }); }); </script> </html> |
Uploading Files to Google Drive
Now guys we will writing the upload request to upload files to google drive. For this you need to make the new file called router.js
file and copy paste the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const stream = require("stream"); const express = require("express"); const multer = require("multer"); const path = require("path"); const { google } = require("googleapis"); const uploadRouter = express.Router(); const upload = multer(); const KEYFILEPATH = path.join(__dirname, "credentials.json"); const SCOPES = ["https://www.googleapis.com/auth/drive"]; const auth = new google.auth.GoogleAuth({ keyFile: KEYFILEPATH, scopes: SCOPES, }); |
As you can see we are including all the libraries needed for this project at the very top. And then we are making the new object of the multer library and then we are including the credentials.json
file which we need to create in the root directory. And then we are adding the scopes
of the google drive. And then we are making the google drive authentication object using the GoogleAuth()
method and inside that we are providing the credentials.json which will be created after you create the service account and also we are adding the scopes also.
Authenticating With Service Account
Now guys we will be creating the service account inside the google cloud console as shown below
After this we need to grant the access to this service account. You need to select the all the rights as owner as shown below
And now we need to create the credentials key json
file as shown below
And now you need to include the credentials.json
file inside the root directory of your project as shown below
Now we will be uploading the files to google drive. We will be writing the custom function as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
uploadRouter.post("/upload", upload.any(), async (req, res) => { try { console.log(req.body); console.log(req.files); const { body, files } = req; for (let f = 0; f < files.length; f += 1) { await uploadFile(files[f]); } console.log(body); res.status(200).send("Form Submitted"); } catch (f) { res.send(f.message); } }); module.exports = uploadRouter; |
As you can see in the above code we are writing the post method to the /upload
route and here we are attaching the middleware function any
of the multer. And then inside it we are receiving the html5 input fields. And here we are looping through all the files selected by the user and here we are calling the custom function which is called uploadFile()
method and inside this method we are passing the files
object.
And now we need to define this custom function of uploadFile()
as shown below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
const uploadFile = async (fileObject) => { const bufferStream = new stream.PassThrough(); bufferStream.end(fileObject.buffer); const { data } = await google.drive({ version: "v3", auth }).files.create({ media: { mimeType: fileObject.mimeType, body: bufferStream, }, requestBody: { name: fileObject.originalname, parents: ["##DRIVEFOLDERID##"], }, fields: "id,name", }); console.log(`Uploaded file ${data.name} ${data.id}`); }; |
As you can see in the above code we are using the drive()
method to upload files to google drive. And here in this method we are passing the drive authentication object. And after that we are using the create()
method to upload the files or media and inside that we are passing the google drive
folder id. For this first of all you need to create the google drive folder and then we need to allow the sharing of the folder to the google service account as shown below
Now if you run the node.js
app by executing the below command as shown below
node index.js