Welcome to our tutorial on serving uploaded files with Node.js! In this lesson, we'll guide you through the process of handling file uploads and serving them from your server.
šÆ Objective: Learn how to handle and serve uploaded files in Node.js.
š Note: This tutorial assumes you have basic knowledge of Node.js and Express.js. If you're new to Node.js, check out our Node.js Tutorial first.
First, let's create a new Express app if you haven't already:
mkdir file-upload-example
cd file-upload-example
npm init -y
npm install express multerHere, we're installing express and multer ā a middleware for handling multipart/form-data, which is primarily used for uploading files.
Create a new file called app.js and add the following code:
const express = require('express');
const multer = require('multer');
const app = express();
const port = 3000;
// Configure multer storage
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
// Create multer upload instance
const upload = multer({ storage });
// Serve static files from the uploads folder
app.use(express.static('uploads'));
// Setup file upload route
app.post('/upload', upload.single('file'), (req, res) => {
// Here you can add logic for saving the uploaded file to a database or perform other actions if needed.
res.send('File uploaded successfully!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});š Note: The app.use(express.static('uploads')) line serves static files from the uploads folder.
Now let's create a simple HTML form to upload a file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload Example</title>
</head>
<body>
<h1>File Upload Form</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
</body>
</html>Save this as index.html in the project root folder.
Start the server by running:
node app.jsOpen your browser and navigate to http://localhost:3000. You should see the file upload form. Upload a file using this form. The file will be saved in the uploads folder, and you'll see a success message: "File uploaded successfully!".
What is the purpose of the `multer` package in our example?
In the next stages of this tutorial, we'll cover:
Stay tuned for more advanced examples!
Happy learning, and don't forget to share your progress with us on CodeYourCraft!
š” Pro Tip: Make sure to test your file uploads on different browsers and devices to ensure they work smoothly.
ā Next Steps:
Happy coding! šš»š