Upload Files to Google Drive Using Express.js
Photo by Growtika on Unsplash
To set up an Express.js server that uploads files to Google Drive API, follow these steps:
1. Enable Google Drive API & Get Credentials
- Go to Google Cloud Console
- Create a new project.
- Enable Google Drive API.
- Go to Credentials → Create credentials → OAuth 2.0 Client ID.
- Download the
credentials.json
file. - Share the
My Drive
folder with the Service Account email (so it has access).
2. Install Required Dependencies
npm init -y
npm install express multer googleapis cors dotenv
3. Setup Express Server (server.js
)
import express from 'express';
import multer from 'multer';
import { google } from 'googleapis';
import fs from 'fs';
import dotenv from 'dotenv';
dotenv.config();
const app = express();
const PORT = 5000;
// Multer setup (store file temporarily)
const upload = multer({ dest: 'uploads/' });
// Google Drive Authentication
const auth = new google.auth.GoogleAuth({
keyFile: 'credentials.json', // Path to the downloaded JSON file
scopes: ['https://www.googleapis.com/auth/drive.file'],
});
const drive = google.drive({ version: 'v3', auth });
// Upload File to Google Drive
const uploadToDrive = async (file) => {
try {
const response = await drive.files.create({
requestBody: {
name: file.originalname,
parents: [process.env.DRIVE_FOLDER_ID], // Your Google Drive folder ID
},
media: {
mimeType: file.mimetype,
body: fs.createReadStream(file.path),
},
});
// Make the file public
await drive.permissions.create({
fileId: response.data.id,
requestBody: { role: 'reader', type: 'anyone' },
});
// Get Public URL
const fileUrl = `https://drive.google.com/uc?id=${response.data.id}`;
return fileUrl;
} catch (error) {
console.error('Error uploading to Google Drive:', error);
return null;
}
};
// Upload Route
app.post('/upload', upload.single('file'), async (req, res) => {
if (!req.file) return res.status(400).json({ error: 'File is required!' });
const fileUrl = await uploadToDrive(req.file);
fs.unlinkSync(req.file.path); // Remove local temp file
if (!fileUrl) return res.status(500).json({ error: 'Upload failed!' });
res.json({ name: req.file.originalname, fileUrl });
});
// Start Server
app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
4. Setup .env
File
Create a .env
file in your project root and add:
DRIVE_FOLDER_ID=YOUR_GOOGLE_DRIVE_FOLDER_ID
(Replace YOUR_GOOGLE_DRIVE_FOLDER_ID
with the actual Google Drive folder ID where you want to store files.)
5. Run the Server
node server.js
6. How to Upload a File
Use Postman or any API client:
- Method:
POST
- URL:
http://localhost:5000/upload
- Form Data:
- Key:
file
- Value: (Choose a file to upload)
- Key:
✅ Response Example:
{
"name": "image.jpg",
"fileUrl": "https://drive.google.com/uc?id=1AbCdEfG123456"
}
Now, the uploaded file is publicly accessible via Google Drive!
Advantages of Using Google Drive API
✅ Free for small projects (15GB storage).
✅ Secure & Scalable (Google-hosted storage).
✅ Public & Private Access Control (Make files public or restrict access).
Let me know if you need any modifications! 🚀