Introduction

While you may upload images on the frontend, you would need to implement an API and database on the backend to receive them. With Multer and Express, a Node.js framework, you can establish file and image uploads in one setting.

In this article, you will learn how to upload images with a Node.js backend using Multer and Express.


Step 1 — Setting Up the Project

As Express is a Node.js framework, ensure that you have Node.js installed from Node.js prior to following the next steps. Run the following in your terminal:

Create a new directory named node-multer-express for your project:

mkdir node-multer-express

Change into the new directory:

cd node-multer-express

Initialize a new Node.js project with defaults. This will include your package.json file to access your dependencies:

npm init

Create your entry file, index.js. This is where you will handle your Express logic:

touch index.js

Install Multer, Express, and morgan as dependencies:

npm install multer express morgan --save

Multer is your image upload library and manages accessing form data from an Express request. morgan is Express middleware for logging network requests.

Applying Multer in Your Project

To set up your Multer library, use the .diskStorage() method to tell Express where to store files to the disk. In your index.js file, require Multer and declare a storage variable and assign its value the invocation of the .diskStorage() method:

index.js

const multer = require('multer');

const storage = multer.diskStorage({
  destination: function(req, file, callback) {
    callback(null, '/src/my-images');
  },
  filename: function (req, file, callback) {
    callback(null, file.fieldname);
  }
});

The destination property on the diskStorage() method determines which directory the files will store. Here, the files will store in the directory, my-images. If you’ve not applied a destination, the operating system will default to a directory for temporary files.

The property filename indicates what to name your files. If you do not set a filename, Multer will return a randomly generated name for your files.

Note: Multer does not add extensions to file names, and it’s recommended to return a filename complete with a file extension.

With your Multer setup complete, let’s combine it within your Express server.

#node #express #image #javascript #developer

How To Upload Images with a Node.js Backend in Multer and Express
2.75 GEEK