7.11. Working with Routes in ExpressJS: Working with File Uploads in Routes

Página 57

ExpressJS is a minimalistic and flexible framework for Node.js that provides a robust set of features for building web and mobile applications. One of the most powerful features ExpressJS offers is the ability to define and work with routes. In this chapter, we'll focus on how to work with file uploads in routes using ExpressJS.

Working with file uploads is a common task in web applications. Whether it's allowing users to upload profile pictures, documents, or any other file type, you'll need to deal with file uploads at some point. Fortunately, ExpressJS makes this relatively simple.

Configuring Middleware

Before we can start accepting file uploads, we need to set up some middleware to process them. Middleware is a function that has access to the request object (req), the response object (res), and the next middleware function in the application's request/response cycle.

To handle file uploads, we are going to use a package called 'multer'. Multer is a node.js middleware to handle 'multipart/form-data' which is used for file upload. It is very easy to use and well documented. To start, you need to install it in your project:

npm install --save mult

Once installed, you can request it in your application and configure a location to store the uploaded files:

const multer = require('multer')
const upload = multer({ dest: 'uploads/' })

Here, we are telling Multer to store the uploaded files in the 'uploads' folder in our root directory.

Defining the Route

With Multer configured, we can now define a route to accept file uploads. Let's define a POST route in '/upload' that accepts a single file:

app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File successfully sent.')
})

In the above route, 'upload.single('file')' is a middleware that processes the upload. 'file' is the name of the field on the form that contains the file. The callback function is called after the file has been successfully loaded.

Working with Uploaded Files

Once a file is uploaded, you can access the file's data through the 'req.file' object. This object contains useful information such as the original file name, the file name on the server, the file type and the file size.

You can use this information to validate the file, rename it, move it, or do anything else you need. Here is an example of how you can rename the file using the 'fs' module of Node.js:

const fs = require('fs')

app.post('/upload', upload.single('file'), (req, res) => {
  fs.rename(req.file.path, 'uploads/' + req.file.originalname, err => {
    if (err) return res.send('Error renaming file.')

    res.send('File successfully sent and renamed.')
  })
})

In this example, we are renaming the file to its original name. If there is an error renaming the file, we send an error message. Otherwise, we send a success message.

Conclusion

Working with file uploads in ExpressJS is simple and straightforward. With Multer middleware, you can easily accept file uploads, access information about uploaded files, and manipulate those files as needed. This is just a basic example of what you can do with file uploads in ExpressJS. The ability to accept and process file uploads is an essential skill for any web developer and is just one of the many powerful features that ExpressJS offers.

Now answer the exercise about the content:

What is the function of the 'multer' middleware in ExpressJS and how is it used to handle file uploads?

You are right! Congratulations, now go to the next page

You missed! Try again.

Next page of the Free Ebook:

587.12. Working with Routes in ExpressJS: Working with JWT Authentication on Routes

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text