-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
86 lines (73 loc) · 2.34 KB
/
app.js
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const express = require('express');
const { google } = require('googleapis');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const credentials = require('./credentials.json');
const app = express();
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
// Initialize Google Drive API client with the service account credentials
const authClient = new google.auth.JWT({
email: credentials.client_email,
key: credentials.private_key,
scopes: ['https://www.googleapis.com/auth/drive'],
});
const appDrive = google.drive({ version: 'v3', auth: authClient });
// Create an upload storage using Multer
const storage = multer.diskStorage({
destination: (req, file, cb) => {
// Set the destination folder where files will be stored temporarily
cb(null, 'uploads');
},
filename: (req, file, cb) => {
// Set the file name to be the original name of the uploaded file
cb(null, file.originalname);
},
});
const upload = multer({ storage: storage });
// Create the "uploads" folder if it doesn't exist
const uploadFolder = './uploads';
if (!fs.existsSync(uploadFolder)) {
fs.mkdirSync(uploadFolder);
}
// Route to render the login page (if needed)
app.get('/', (req, res) => {
res.render('login');
});
// Route to render the file upload page
app.get('/upload', (req, res) => {
res.render('upload');
});
// Route to handle file upload
app.post('/upload', upload.single('file'), async (req, res) => {
if (!req.file) {
res.status(400).send('No file uploaded.');
return;
}
const fileMetadata = {
name: req.file.originalname,
parents: ['1HVpdB13RVlZJcMoyi6Cl1uqyLgxXNGKj'], // Replace with the actual parent folder ID
};
const media = {
mimeType: req.file.mimetype,
body: fs.createReadStream(req.file.path), // Read the file from disk
};
try {
const response = await appDrive.files.create({
resource: fileMetadata,
media: media,
fields: 'id',
});
console.log('File uploaded with ID:', response.data.id);
res.send('File uploaded successfully.');
} catch (error) {
console.error('Error uploading file:', error.message);
res.status(500).send('Error uploading file.');
}
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});