File Upload With Multer in Node.js and Express
This tutorial guides you through building a file upload system using Node.js, Express, and Multer. We'll cover single and multiple file uploads, and even demonstrate storing images in a MongoDB database for later retrieval.
First, set up your project:
mkdir upload-express cd upload-express npm init -y npm install express multer mongodb file-system --save touch server.js mkdir uploads
Next, create your server.js
file. This will handle the file uploads and server logic. Initially, we'll set up a basic Express app:
const express = require('express'); const multer = require('multer'); const app = express(); app.get('/', (req, res) => { res.json({ message: 'WELCOME' }); }); app.listen(3000, () => console.log('Server started on port 3000'));
Now, let's configure Multer to handle file uploads to disk:
//server.js (add this to your existing server.js) var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, 'uploads') }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now()) } }); var upload = multer({ storage: storage });
Handling File Uploads
Single File Upload
Create an endpoint to handle single file uploads. Remember to create a corresponding <form></form>
with a file input in your index.html
(not shown here, but should use a POST request to /uploadfile
).
//server.js (add this to your existing server.js) app.post('/uploadfile', upload.single('myFile'), (req, res, next) => { const file = req.file; if (!file) { const error = new Error('Please upload a file'); error.httpStatusCode = 400; return next(error); } res.send(file); });
Multiple File Uploads
This endpoint handles uploading multiple files (up to 12 in this example):
//server.js (add this to your existing server.js) app.post('/uploadmultiple', upload.array('myFiles', 12), (req, res, next) => { const files = req.files; if (!files) { const error = new Error('Please choose files'); error.httpStatusCode = 400; return next(error); } res.send(files); });
Image Upload to MongoDB
To store images in MongoDB, we'll need to install the mongodb
package:
npm install mongodb --save
Then, add the MongoDB connection and image handling logic to server.js
. (Note: Error handling and connection details are omitted for brevity. Replace placeholders like <your_mongodb_connection_string></your_mongodb_connection_string>
with your actual connection string).
const { MongoClient } = require('mongodb'); const fs = require('file-system'); // For file system operations // ... (previous code) ... const client = new MongoClient("<your_mongodb_connection_string>"); // ... (rest of your code) ... app.post('/uploadImage', upload.single('myImage'), async (req, res) => { try { await client.connect(); const db = client.db('your_database_name'); const imageBuffer = fs.readFileSync(req.file.path); const result = await db.collection('images').insertOne({ image: { filename: req.file.filename, buffer: imageBuffer } }); res.send(result); } catch (error) { console.error(error); res.status(500).send("Error uploading image"); } finally { await client.close(); } }); app.get('/photos', async (req, res) => { try { await client.connect(); const db = client.db('your_database_name'); const result = await db.collection('images').find().toArray(); const imgArray = result.map(element => element._id); res.send(imgArray); } catch (error) { console.error(error); res.status(500).send("Error retrieving images"); } finally { await client.close(); } }); app.get('/photo/:id', async (req, res) => { try { await client.connect(); const db = client.db('your_database_name'); const result = await db.collection('images').findOne({ _id: new ObjectId(req.params.id) }); res.contentType('image/jpeg'); // Adjust content type as needed res.send(result.image.buffer); } catch (error) { console.error(error); res.status(500).send("Error retrieving image"); } finally { await client.close(); } }); // ... (rest of your code) ...</your_mongodb_connection_string>
Remember to install the mongodb
and file-system
packages. Also replace placeholders with your database name and connection string. This improved example includes error handling and asynchronous operations for better robustness.
This enhanced tutorial provides a more complete and robust solution for handling file uploads in a Node.js application. Remember to adapt the code to your specific needs and environment. Always prioritize security best practices when handling file uploads in production.
The above is the detailed content of File Upload With Multer in Node.js and Express. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

PHP templating often gets a bad rap for facilitating subpar code — but that doesn't have to be the case. Let’s look at how PHP projects can enforce a basic

We are always looking to make the web more accessible. Color contrast is just math, so Sass can help cover edge cases that designers might have missed.
