Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const multer = require('multer');
- const path = require('path');
- const mongoose = require('mongoose');
- // Set up the MongoDB connection
- mongoose.connect('mongodb://localhost/file_upload', { useNewUrlParser: true, useUnifiedTopology: true });
- const db = mongoose.connection;
- db.on('error', console.error.bind(console, 'MongoDB connection error:'));
- db.once('open', () => {
- console.log('Connected to MongoDB');
- });
- // Create a schema for the uploaded files
- const fileSchema = new mongoose.Schema({
- filename: String,
- originalname: String,
- mimetype: String,
- size: Number,
- uploadDate: { type: Date, default: Date.now }
- });
- const File = mongoose.model('File', fileSchema);
- // Set up the storage for uploaded files
- const storage = multer.diskStorage({
- destination: './uploads',
- filename: function (req, file, cb) {
- cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
- }
- });
- // Create multer instance
- const upload = multer({ storage });
- // Create Express app
- const app = express();
- // Serve static files from the "public" directory
- app.use(express.static('public'));
- // Route for the file upload form
- app.get('/', (req, res) => {
- res.sendFile(path.join(__dirname, 'public', 'index.html'));
- });
- // Route for handling file upload
- app.post('/upload', upload.single('file'), async (req, res) => {
- if (req.file) {
- const uploadedFile = new File({
- filename: req.file.filename,
- originalname: req.file.originalname,
- mimetype: req.file.mimetype,
- size: req.file.size
- });
- try {
- await uploadedFile.save();
- res.send('File uploaded successfully!');
- } catch (error) {
- res.status(500).send('Error saving file to database.');
- }
- } else {
- res.status(400).send('No file uploaded.');
- }
- });
- // Route for retrieving all uploaded files
- app.get('/files', async (req, res) => {
- try {
- const files = await File.find().sort('-uploadDate');
- res.json(files);
- } catch (error) {
- res.status(500).send('Error retrieving files from database.');
- }
- });
- // Route for retrieving a specific uploaded file
- app.get('/files/:id', async (req, res) => {
- try {
- const file = await File.findById(req.params.id);
- res.json(file);
- } catch (error) {
- res.status(500).send('Error retrieving file from database.');
- }
- });
- // Route for deleting a specific uploaded file
- app.delete('/files/:id', async (req, res) => {
- try {
- const file = await File.findByIdAndDelete(req.params.id);
- res.send('File deleted successfully!');
- } catch (error) {
- res.status(500).send('Error deleting file from database.');
- }
- });
- // Route for updating a specific uploaded file
- app.put('/files/:id', async (req, res) => {
- try {
- const fileId = req.params.id;
- const { filename, originalname, mimetype, size } = req.body;
- const updatedFile = await File.findByIdAndUpdate(fileId, {
- filename,
- originalname,
- mimetype,
- size
- });
- if (updatedFile) {
- res.send('File updated successfully!');
- } else {
- res.status(404).send('File not found.');
- }
- } catch (error) {
- res.status(500).send('Error updating file.');
- }
- });
- // Start the server
- const port = 3000;
- app.listen(port, () => {
- console.log(`Server is listening on port ${port}`);
- });
- <!DOCTYPE html>
- <html>
- <head>
- <title>File Upload Form</title>
- </head>
- <body>
- <h1>File Upload</h1>
- <form action="/upload" method="post" enctype="multipart/form-data">
- <input type="file" name="file" />
- <input type="submit" value="Upload" />
- </form>
- <h1>Uploaded Files</h1>
- <ul id="fileList"></ul>
- <script>
- // Fetch uploaded files and display them in the list
- fetch('/files')
- .then((response) => response.json())
- .then((data) => {
- const fileList = document.getElementById('fileList');
- data.forEach((file) => {
- const listItem = document.createElement('li');
- listItem.textContent = file.originalname;
- fileList.appendChild(listItem);
- });
- });
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement