I Cant Upload File With Multer on Postman Error

In this tutorial, I will show you how to upload file with Node.js Express Rest APIs to/from a static folder using Multer (with file size limit).

This Node.js App works with:
– Angular 8 Client / Angular ten Client / Angular xi Client / Angular 12
– Angular Material 12
– Vue Client / Vuetify Client
– React Client / React Hooks Client
– Textile UI Client
– Axios Client

Related Posts:
– Google Cloud Storage with Node.js: File Upload example
– How to upload multiple files in Node.js
– Upload/store images in MySQL using Node.js, Express & Multer
– How to upload/store images in MongoDB using Node.js, Express & Multer
– Node.js Residual APIs example with Limited, Sequelize & MySQL

Node.js Express Rest APIs for uploading Files

Our Node.js Application will provide APIs for:

  • uploading File to a static folder in the Server (restrict file size: 2MB)
  • downloading File from server with the link
  • getting list of Files' data (file proper noun & url)

This is the static folder that stores all uploaded files:

upload-file-node-js-express-rest-api-file-upload-folder

If we get list of files, the Node.js Residual Apis volition return:

upload-file-node-js-express-rest-api-file-upload-list-response

Each item in the response array has a url that you tin use for downloading the file.

These are APIs to be exported:

Methods Urls Actions
POST /upload upload a File
GET /files become List of Files (name & url)
GET /files/[filename] download a File

Technology

  • express 4.17.1
  • multer 1.4.two
  • cors two.8.5

Project Structure

This is the project directory that nosotros're gonna build:

upload-file-node-js-express-rest-api-file-upload-project-structure

resources/static/assets/uploads: binder for storing uploaded files.
middleware/upload.js: initializes Multer Storage engine and defines middleware function to salve uploaded files in uploads binder.
file.controller.js exports Residue APIs: POST a file, GET all files' information, download a File with url.
routes/index.js: defines routes for endpoints that is called from HTTP Customer, employ controller to handle requests.
server.js: initializes routes, runs Limited app.

Setup Node.js Express File Upload project

Open command prompt, change electric current directory to the root folder of our project.
Install Limited, Multer, CORS modules with the post-obit control:

          npm install limited multer cors                  

The package.json file will look similar this:

          {   "proper name": "node-js-express-upload-download-files",   "version": "1.0.0",   "clarification": "Node.js Limited Rest APis to Upload/Download Files",   "main": "server.js",   "scripts": {     "test": "echo \"Error: no test specified\" && get out 1"   },   "keywords": [     "node js",     "upload",     "download",     "file",     "multipart",     "rest api",     "limited"   ],   "author": "bezkoder",   "license": "ISC",   "dependencies": {     "cors": "^2.8.v",     "express": "^4.17.1",     "multer": "^ane.4.two"   } }                  

Create middleware for file upload

The middleware will utilize Multer for treatment multipart/course-information along with uploading files.

Inside middleware folder, create upload.js file:

          const util = crave("util"); const multer = crave("multer"); const maxSize = 2 * 1024 * 1024; permit storage = multer.diskStorage({   destination: (req, file, cb) => {     cb(null, __basedir + "/resource/static/avails/uploads/");   },   filename: (req, file, cb) => {     console.log(file.originalname);     cb(null, file.originalname);   }, }); let uploadFile = multer({   storage: storage,   limits: { fileSize: maxSize }, }).single("file"); let uploadFileMiddleware = util.promisify(uploadFile); module.exports = uploadFileMiddleware;                  

In the code in a higher place, nosotros've done these steps:
– First, nosotros import multer module.
– Next, nosotros configure multer to use Disk Storage engine.

You can meet that we have 2 options hither:
destination determines folder to store the uploaded files.
filename determines the name of the file within the destination folder.

util.promisify() makes the exported middleware object tin can exist used with async-wait.

Restrict file size with Multer

With the new multer API. Nosotros tin add limits: { fileSize: maxSize } to the object passed to multer() to restrict file size.

          let storage = multer.diskStorage(...); const maxSize = ii * 1024 * 1024; let uploadFile = multer({   storage: storage,   limits: { fileSize: maxSize } }).single("file");                  

Create Controller for file upload/download

In controller binder, create file.controller.js:

– For File Upload method, we will export upload() function that:

  • use middleware role for file upload
  • grab Multer fault (in middleware function)
  • return response with message

– For File Information and Download:

  • getListFiles(): read all files in uploads folder, return list of files' information (proper name, url)
  • download(): receives file name as input parameter, and so uses Limited res.download API to transfer the file at path (directory + file name) equally an 'attachment'.
          const uploadFile = require("../middleware/upload"); const upload = async (req, res) => {   try {     await uploadFile(req, res);     if (req.file == undefined) {       return res.status(400).transport({ message: "Delight upload a file!" });     }     res.status(200).send({       message: "Uploaded the file successfully: " + req.file.originalname,     });   } catch (err) {     res.condition(500).ship({       bulletin: `Could not upload the file: ${req.file.originalname}. ${err}`,     });   } }; const getListFiles = (req, res) => {   const directoryPath = __basedir + "/resources/static/avails/uploads/";   fs.readdir(directoryPath, role (err, files) {     if (err) {       res.status(500).ship({         message: "Unable to scan files!",       });     }     allow fileInfos = [];     files.forEach((file) => {       fileInfos.push({         proper noun: file,         url: baseUrl + file,       });     });     res.condition(200).send(fileInfos);   }); }; const download = (req, res) => {   const fileName = req.params.name;   const directoryPath = __basedir + "/resources/static/assets/uploads/";   res.download(directoryPath + fileName, fileName, (err) => {     if (err) {       res.condition(500).transport({         message: "Could not download the file. " + err,       });     }   }); }; module.exports = {   upload,   getListFiles,   download, };                  

– We call middleware function uploadFile() first.
– If the HTTP asking doesn't include a file, ship 400 status in the response.
– We also catch the error and send 500 status with mistake message.

So, how to handle the example in that user uploads the file exceeding size limitation?

Handle Multer file size limit error

We can handle the error past checking error code (LIMIT_FILE_SIZE) in the catch() block:

          const upload = async (req, res) => {   try {     wait uploadFile(req, res);     ...   } take hold of (err) {     if (err.code == "LIMIT_FILE_SIZE") {       return res.status(500).send({         bulletin: "File size cannot be larger than 2MB!",       });     }     res.condition(500).ship({       message: `Could not upload the file: ${req.file.originalname}. ${err}`,     });   } };                  

Ascertain Route for uploading file

When a client sends HTTP requests, we demand to determine how the server will response by setting up the routes.

There are iii routes with respective controller methods:

  • POST /upload: upload()
  • GET /files: getListFiles()
  • GET /files/[fileName]: download()

Create index.js file inside routes folder with content like this:

          const express = crave("express"); const router = express.Router(); const controller = require("../controller/file.controller"); allow routes = (app) => {   router.mail service("/upload", controller.upload);   router.become("/files", controller.getListFiles);   router.become("/files/:proper noun", controller.download);   app.utilise(router); }; module.exports = routes;                  

Yous can come across that we use controller from file.controller.js.

Create Express app server

Finally, we create an Express server in server.js:

          const cors = require("cors"); const express = require("express"); const app = express(); global.__basedir = __dirname; var corsOptions = {   origin: "http://localhost:8081" }; app.use(cors(corsOptions)); const initRoutes = require("./src/routes"); app.use(express.urlencoded({ extended: true })); initRoutes(app); permit port = 8080; app.listen(port, () => {   console.log(`Running at localhost:${port}`); });                  

What we do are:
– import express and cors modules:

  • Express is for building the Rest apis
  • cors provides Express middleware to enable CORS with various options.

– create an Express app, then add cors middlewares using app.utilize() method. Observe that we set up origin: http://localhost:8081.
– listen on port 8080 for incoming requests.

Run & Test

Outset nosotros need to create uploads folder with the path resource/static/avails.
On the projection root binder, run this control: node server.js.

Let's use Postman to brand HTTP POST request with a file.

upload-file-node-js-express-rest-api-file-upload

– Upload a file with size larger than max file size (2MB):

upload-file-node-js-express-rest-api-file-upload-limit-size

– Cheque uploads folder after uploading several files:

upload-file-node-js-express-rest-api-file-upload-folder

– Recall listing of Files' information:

upload-file-node-js-express-rest-api-file-upload-list-response

– Now you tin download any file from i of the paths to a higher place.
For example: http://localhost:8080/files/bezkoder.png.

Conclusion

Today we've learned how to create Node.js Express Residuum API to upload file into static binder using Multer for middleware handling multipart file. You also know how to restrict file size and catch Multer file size limit error.

Following tutorials explain how to build Front-end Apps to work with our Node.js Express Server:
– Angular 8 Client / Athwart 10 Client / Angular 11 Client / Athwart 12
– Athwart Material 12
– Vue Client / Vuetify Client
– React Customer / React Hooks Client
– Material UI Client
– React Image Upload with Preview
– Axios Client

For multiple Files at once:
How to upload multiple files in Node.js

Upload to GCS:
Google Cloud Storage with Node.js: File Upload example

You tin likewise know way to upload an Excel file and store the content in MySQL database with the post:
Node.js: Upload/Import Excel file data into Database

If you want to upload images into database, you can find instructions at:
– Upload/store images in MySQL using Node.js, Express & Multer
– How to upload/store images in MongoDB using Node.js, Express & Multer

Happy Learning! Run across you again.

Further Reading

  • https://world wide web.npmjs.com/package/express
  • https://www.npmjs.com/package/multer

Source Code

You tin can find the complete source code for this tutorial on Github.

leemajew1957.blogspot.com

Source: https://www.bezkoder.com/node-js-express-file-upload/

0 Response to "I Cant Upload File With Multer on Postman Error"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel