Advertisement
sourav8256

nodejs server

Jun 30th, 2023 (edited)
836
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express');
  2. const multer = require('multer');
  3. const path = require('path');
  4. const mongoose = require('mongoose');
  5.  
  6. // Set up the MongoDB connection
  7. mongoose.connect('mongodb://localhost/file_upload', { useNewUrlParser: true, useUnifiedTopology: true });
  8. const db = mongoose.connection;
  9. db.on('error', console.error.bind(console, 'MongoDB connection error:'));
  10. db.once('open', () => {
  11.   console.log('Connected to MongoDB');
  12. });
  13.  
  14. // Create a schema for the uploaded files
  15. const fileSchema = new mongoose.Schema({
  16.   filename: String,
  17.   originalname: String,
  18.   mimetype: String,
  19.   size: Number,
  20.   uploadDate: { type: Date, default: Date.now }
  21. });
  22.  
  23. const File = mongoose.model('File', fileSchema);
  24.  
  25. // Set up the storage for uploaded files
  26. const storage = multer.diskStorage({
  27.   destination: './uploads',
  28.   filename: function (req, file, cb) {
  29.     cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
  30.   }
  31. });
  32.  
  33. // Create multer instance
  34. const upload = multer({ storage });
  35.  
  36. // Create Express app
  37. const app = express();
  38.  
  39. // Serve static files from the "public" directory
  40. app.use(express.static('public'));
  41.  
  42. // Route for the file upload form
  43. app.get('/', (req, res) => {
  44.   res.sendFile(path.join(__dirname, 'public', 'index.html'));
  45. });
  46.  
  47. // Route for handling file upload
  48. app.post('/upload', upload.single('file'), async (req, res) => {
  49.   if (req.file) {
  50.     const uploadedFile = new File({
  51.       filename: req.file.filename,
  52.       originalname: req.file.originalname,
  53.       mimetype: req.file.mimetype,
  54.       size: req.file.size
  55.     });
  56.  
  57.     try {
  58.       await uploadedFile.save();
  59.       res.send('File uploaded successfully!');
  60.     } catch (error) {
  61.       res.status(500).send('Error saving file to database.');
  62.     }
  63.   } else {
  64.     res.status(400).send('No file uploaded.');
  65.   }
  66. });
  67.  
  68. // Route for retrieving all uploaded files
  69. app.get('/files', async (req, res) => {
  70.   try {
  71.     const files = await File.find().sort('-uploadDate');
  72.     res.json(files);
  73.   } catch (error) {
  74.     res.status(500).send('Error retrieving files from database.');
  75.   }
  76. });
  77.  
  78. // Route for retrieving a specific uploaded file
  79. app.get('/files/:id', async (req, res) => {
  80.   try {
  81.     const file = await File.findById(req.params.id);
  82.     res.json(file);
  83.   } catch (error) {
  84.     res.status(500).send('Error retrieving file from database.');
  85.   }
  86. });
  87.  
  88. // Route for deleting a specific uploaded file
  89. app.delete('/files/:id', async (req, res) => {
  90.   try {
  91.     const file = await File.findByIdAndDelete(req.params.id);
  92.     res.send('File deleted successfully!');
  93.   } catch (error) {
  94.     res.status(500).send('Error deleting file from database.');
  95.   }
  96. });
  97.  
  98. // Route for updating a specific uploaded file
  99. app.put('/files/:id', async (req, res) => {
  100.   try {
  101.     const fileId = req.params.id;
  102.     const { filename, originalname, mimetype, size } = req.body;
  103.  
  104.     const updatedFile = await File.findByIdAndUpdate(fileId, {
  105.       filename,
  106.       originalname,
  107.       mimetype,
  108.       size
  109.     });
  110.  
  111.     if (updatedFile) {
  112.       res.send('File updated successfully!');
  113.     } else {
  114.       res.status(404).send('File not found.');
  115.     }
  116.   } catch (error) {
  117.     res.status(500).send('Error updating file.');
  118.   }
  119. });
  120.  
  121. // Start the server
  122. const port = 3000;
  123. app.listen(port, () => {
  124.   console.log(`Server is listening on port ${port}`);
  125. });
  126.  
  127.  
  128.  
  129.  
  130. <!DOCTYPE html>
  131. <html>
  132.   <head>
  133.     <title>File Upload Form</title>
  134.   </head>
  135.   <body>
  136.     <h1>File Upload</h1>
  137.     <form action="/upload" method="post" enctype="multipart/form-data">
  138.       <input type="file" name="file" />
  139.       <input type="submit" value="Upload" />
  140.     </form>
  141.  
  142.     <h1>Uploaded Files</h1>
  143.     <ul id="fileList"></ul>
  144.  
  145.     <script>
  146.       // Fetch uploaded files and display them in the list
  147.       fetch('/files')
  148.         .then((response) => response.json())
  149.         .then((data) => {
  150.           const fileList = document.getElementById('fileList');
  151.           data.forEach((file) => {
  152.             const listItem = document.createElement('li');
  153.             listItem.textContent = file.originalname;
  154.             fileList.appendChild(listItem);
  155.           });
  156.         });
  157.     </script>
  158.   </body>
  159. </html>
  160.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement