Spaces:
Build error
Build error
| const express = require('express'); | |
| const multer = require('multer'); | |
| const { google } = require('googleapis'); | |
| const fs = require('fs'); | |
| const path = require('path'); | |
| const app = express(); | |
| // Konfigurasi multer untuk menangani upload file | |
| const upload = multer({ dest: 'uploads/' }); | |
| // Setup Google Drive API credentials | |
| const CLIENT_ID = process.env.GOOGLE_DRIVE_CLIENT_ID; | |
| const CLIENT_SECRET = process.env.GOOGLE_DRIVE_CLIENT_SECRET; | |
| const REFRESH_TOKEN = process.env.GOOGLE_DRIVE_REFRESH_TOKEN; | |
| const FOLDER_ID = process.env.GOOGLE_DRIVE_FOLDER_ID; | |
| const oauth2Client = new google.auth.OAuth2( | |
| CLIENT_ID, | |
| CLIENT_SECRET, | |
| "https://developers.google.com/oauthplayground" // Redirect URL (tidak digunakan) | |
| ); | |
| oauth2Client.setCredentials({ | |
| refresh_token: REFRESH_TOKEN, | |
| }); | |
| const drive = google.drive({ | |
| version: 'v3', | |
| auth: oauth2Client, | |
| }); | |
| // Function to upload file to Google Drive | |
| async function uploadFileToGoogleDrive(file) { | |
| try { | |
| const fileMetadata = { | |
| 'name': file.originalname, | |
| 'parents': [FOLDER_ID], // Folder ID tempat file akan disimpan | |
| }; | |
| const media = { | |
| mimeType: file.mimetype, | |
| body: fs.createReadStream(file.path), | |
| }; | |
| const response = await drive.files.create({ | |
| resource: fileMetadata, | |
| media: media, | |
| fields: 'id', | |
| }); | |
| return response.data.id; | |
| } catch (error) { | |
| throw new Error('Gagal mengunggah ke Google Drive: ' + error.message); | |
| } | |
| } | |
| // Endpoint untuk upload file | |
| app.post('/upload', upload.single('file'), async (req, res) => { | |
| try { | |
| if (!req.file) { | |
| return res.status(400).send('No file uploaded.'); | |
| } | |
| const fileId = await uploadFileToGoogleDrive(req.file); | |
| // Hapus file lokal setelah diunggah ke Google Drive | |
| fs.unlinkSync(req.file.path); | |
| res.json({ | |
| message: 'File uploaded successfully to Google Drive!', | |
| fileId: fileId, | |
| }); | |
| } catch (error) { | |
| res.status(500).send('Error uploading file: ' + error.message); | |
| } | |
| }); | |
| // Start server | |
| const PORT = process.env.PORT || 3000; | |
| app.listen(PORT, () => { | |
| console.log(`Server running on port ${PORT}`); | |
| }); | |