Serving Uploaded Files with Node.js

beginner
22 min

Serving Uploaded Files with Node.js

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.

Introduction

šŸŽÆ 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.

Creating a New Express App

First, let's create a new Express app if you haven't already:

bash
mkdir file-upload-example cd file-upload-example npm init -y npm install express multer

Here, we're installing express and multer – a middleware for handling multipart/form-data, which is primarily used for uploading files.

Setting Up the Server

Create a new file called app.js and add the following code:

javascript
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.

Uploading a File

Now let's create a simple HTML form to upload a file:

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 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.

Testing the Application

Start the server by running:

bash
node app.js

Open 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!".

Quiz

Quick Quiz
Question 1 of 1

What is the purpose of the `multer` package in our example?

Advanced Examples

In the next stages of this tutorial, we'll cover:

  1. Storing uploaded files in a database: Learn how to store uploaded files in a database like MongoDB.
  2. Limiting file size and types: Discover how to limit the size and types of uploaded files.
  3. Handling multiple file uploads: Explore handling multiple file uploads in a single request.
  4. Saving uploaded files in Amazon S3: Learn how to save uploaded files in Amazon S3.

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:

  1. Practice uploading files using the example provided.
  2. Implement the advanced examples mentioned above to extend your knowledge.
  3. Experiment with different file types and sizes to get familiar with handling real-world scenarios.

Happy coding! šŸš€šŸ’»šŸŽ“