How to Upload Files Using express-fileupload in an Express.js Project: Step-by-Step Guide
Step 1: Install express-fileupload
First, you need to install the express-fileupload package.
Run this command in your project folder:
npm install express-fileupload
Step 2: Set Up Express and Import express-fileupload
In your main app.js or server.js file, set up Express and import express-fileupload.
const express = require('express');
const fileUpload = require('express-fileupload');
const path = require('path');
const app = express();
Step 3: Use express-fileupload Middleware
Next, add express-fileupload as middleware to your Express app. This will allow you to handle file uploads.
// Enable files upload
app.use(fileUpload());
Step 4: Create an HTML Form for File Upload
You need a frontend where users can upload files. Create an HTML form that sends a file to the server using a POST request.
Here’s an example form in an HTML file (e.g., index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<form ref='uploadForm'
id='uploadForm'
action='/upload'
method='post'
encType="multipart/form-data">
<input type="file" name="file" />
<input type='submit' value='Upload!' />
</form>
</body>
</html>
Step 5: Create the Upload Route in Express
Now, you’ll create a route to handle the file upload. This route will capture the file sent from the form, and then store it on the server.
领英推荐
app.post('/upload', (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// Access the file through req.files.<input_name>
let uploadedFile = req.files.file;
// Set the file upload path
const uploadPath = path.join(__dirname, 'uploads', uploadedFile.name);
// Use the mv() method to place the file in the desired directory
uploadedFile.mv(uploadPath, (err) => {
if (err) {
return res.status(500).send(err);
}
res.send('File uploaded successfully!');
});
});
Step 6: Create an Uploads Directory
Create a folder named uploads in your project’s root directory where the uploaded files will be stored.
mkdir uploads
Step 7: Serve Static Files (Optional)
If you want to allow users to access uploaded files, you can serve them as static files by adding this line:
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
Step 8: Start the Server
Finally, start your Express server and visit the form in your browser to upload a file.
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on https://localhost:${PORT}`);
});
Full Example
const express = require('express');
const fileUpload = require('express-fileupload');
const path = require('path');
const app = express();
// Middleware to handle file uploads
app.use(fileUpload());
// Serve static files from the 'uploads' directory
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
// Upload route
app.post('/upload', (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
let uploadedFile = req.files.file;
const uploadPath = path.join(__dirname, 'uploads', uploadedFile.name);
uploadedFile.mv(uploadPath, (err) => {
if (err) {
return res.status(500).send(err);
}
res.send('File uploaded successfully!');
});
});
// Start server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on https://localhost:${PORT}`);
});
Step 9: Test the File Upload
Notes
Full-Stack Web Developer (JavaScript) & CMS (WordPress, Shopify) Expert
4 个月Thanks Amit vai. For explain in details.