How Are File Uploads Handled on the Server Nodej
In this tutorial, I will prove 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 viii Client / Angular 10 Client / Angular 11 Customer / Angular 12
– Angular Fabric 12
– Vue Client / Vuetify Customer
– React Client / React Hooks Client
– Material UI Client
– Axios Client
Related Posts:
– Google Deject 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 Rest APIs example with Express, Sequelize & MySQL
Node.js Express Residuum 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 listing of Files' data (file name & url)
This is the static folder that stores all uploaded files:
If nosotros become list of files, the Node.js Remainder Apis will return:
Each particular in the response assortment has a url that you tin can utilise for downloading the file.
These are APIs to be exported:
| Methods | Urls | Actions |
|---|---|---|
| POST | /upload | upload a File |
| GET | /files | get List of Files (name & url) |
| Become | /files/[filename] | download a File |
Technology
- express 4.17.1
- multer i.4.2
- cors 2.viii.5
Project Structure
This is the projection directory that nosotros're gonna build:
– resources/static/avails/uploads: folder for storing uploaded files.
– middleware/upload.js: initializes Multer Storage engine and defines middleware function to save uploaded files in uploads binder.
– file.controller.js exports Rest APIs: Mail service a file, GET all files' data, download a File with url.
– routes/index.js: defines routes for endpoints that is chosen from HTTP Customer, utilise controller to handle requests.
– server.js: initializes routes, runs Express app.
Setup Node.js Express File Upload project
Open command prompt, change current directory to the root folder of our project.
Install Express, Multer, CORS modules with the following command:
npm install express multer cors The parcel.json file volition look like this:
{ "proper noun": "node-js-express-upload-download-files", "version": "ane.0.0", "description": "Node.js Express Residuum APis to Upload/Download Files", "main": "server.js", "scripts": { "test": "echo \"Error: no examination specified\" && leave i" }, "keywords": [ "node js", "upload", "download", "file", "multipart", "residue api", "limited" ], "author": "bezkoder", "license": "ISC", "dependencies": { "cors": "^ii.8.5", "express": "^iv.17.i", "multer": "^one.4.2" } } Create middleware for file upload
The middleware will use Multer for handling multipart/form-data along with uploading files.
Inside middleware folder, create upload.js file:
const util = require("util"); const multer = require("multer"); const maxSize = two * 1024 * 1024; allow storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, __basedir + "/resources/static/assets/uploads/"); }, filename: (req, file, cb) => { console.log(file.originalname); cb(null, file.originalname); }, }); permit uploadFile = multer({ storage: storage, limits: { fileSize: maxSize }, }).single("file"); let uploadFileMiddleware = util.promisify(uploadFile); module.exports = uploadFileMiddleware; In the code in a higher place, we've washed these steps:
– First, nosotros import multer module.
– Next, we configure multer to use Disk Storage engine.
You can encounter that we have two options hither:
– destination determines binder to shop the uploaded files.
– filename determines the name of the file inside the destination binder.
util.promisify() makes the exported middleware object can exist used with async-expect.
Restrict file size with Multer
With the new multer API. We tin add limits: { fileSize: maxSize } to the object passed to multer() to restrict file size.
let storage = multer.diskStorage(...); const maxSize = 2 * 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 consign upload() function that:
- use middleware function for file upload
- catch Multer error (in middleware office)
- return response with message
– For File Information and Download:
-
getListFiles(): read all files in uploads folder, render list of files' information (name, url) -
download(): receives file name every bit input parameter, then uses Limited res.download API to transfer the file at path (directory + file name) as an 'attachment'.
const uploadFile = crave("../middleware/upload"); const upload = async (req, res) => { endeavor { await uploadFile(req, res); if (req.file == undefined) { return res.status(400).send({ message: "Please upload a file!" }); } res.status(200).send({ message: "Uploaded the file successfully: " + req.file.originalname, }); } catch (err) { res.status(500).send({ bulletin: `Could non upload the file: ${req.file.originalname}. ${err}`, }); } }; const getListFiles = (req, res) => { const directoryPath = __basedir + "/resources/static/avails/uploads/"; fs.readdir(directoryPath, part (err, files) { if (err) { res.condition(500).send({ message: "Unable to scan files!", }); } let fileInfos = []; files.forEach((file) => { fileInfos.push({ proper name: file, url: baseUrl + file, }); }); res.status(200).send(fileInfos); }); }; const download = (req, res) => { const fileName = req.params.name; const directoryPath = __basedir + "/resources/static/avails/uploads/"; res.download(directoryPath + fileName, fileName, (err) => { if (err) { res.status(500).send({ message: "Could not download the file. " + err, }); } }); }; module.exports = { upload, getListFiles, download, }; – Nosotros telephone call middleware function uploadFile() first.
– If the HTTP request doesn't include a file, transport 400 condition in the response.
– Nosotros too catch the fault and transport 500 status with error bulletin.
Then, how to handle the example in that user uploads the file exceeding size limitation?
Handle Multer file size limit error
Nosotros tin can handle the error past checking error code (LIMIT_FILE_SIZE) in the grab() cake:
const upload = async (req, res) => { endeavour { expect uploadFile(req, res); ... } catch (err) { if (err.code == "LIMIT_FILE_SIZE") { return res.status(500).send({ bulletin: "File size cannot be larger than 2MB!", }); } res.status(500).transport({ message: `Could non upload the file: ${req.file.originalname}. ${err}`, }); } }; Define Road for uploading file
When a client sends HTTP requests, we demand to determine how the server will response by setting up the routes.
In that location are 3 routes with corresponding controller methods:
- Post
/upload:upload() - GET
/files:getListFiles() - GET
/files/[fileName]:download()
Create index.js file inside routes folder with content like this:
const limited = require("limited"); const router = limited.Router(); const controller = require("../controller/file.controller"); let routes = (app) => { router.postal service("/upload", controller.upload); router.go("/files", controller.getListFiles); router.go("/files/:name", controller.download); app.use(router); }; module.exports = routes; You tin can run into that we utilise controller from file.controller.js.
Create Limited app server
Finally, we create an Limited server in server.js:
const cors = require("cors"); const express = crave("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); allow port = 8080; app.heed(port, () => { console.log(`Running at localhost:${port}`); }); What we practice are:
– import limited and cors modules:
- Express is for building the Residue apis
- cors provides Express middleware to enable CORS with various options.
– create an Express app, then add cors middlewares using app.use() method. Notice that we set origin: http://localhost:8081.
– mind on port 8080 for incoming requests.
Run & Test
Outset we need to create uploads binder with the path resource/static/assets.
On the projection root folder, run this command: node server.js.
Let's use Postman to brand HTTP Postal service asking with a file.
– Upload a file with size larger than max file size (2MB):
– Cheque uploads folder afterwards uploading several files:
– Retrieve list of Files' data:
– Now you can download any file from 1 of the paths above.
For example: http://localhost:8080/files/bezkoder.png.
Conclusion
Today we've learned how to create Node.js Express Rest API to upload file into static folder using Multer for middleware treatment 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 Limited Server:
– Athwart 8 Client / Angular ten Client / Athwart 11 Client / Angular 12
– Angular Material 12
– Vue Customer / Vuetify Client
– React Client / React Hooks Customer
– Cloth UI Client
– React Image Upload with Preview
– Axios Customer
For multiple Files at once:
How to upload multiple files in Node.js
Upload to GCS:
Google Deject Storage with Node.js: File Upload case
You can also 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 desire 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, Limited & Multer
Happy Learning! See you again.
Farther Reading
- https://www.npmjs.com/package/express
- https://www.npmjs.com/package/multer
Source Code
You lot can find the complete source code for this tutorial on Github.
Source: https://www.bezkoder.com/node-js-express-file-upload/
0 Response to "How Are File Uploads Handled on the Server Nodej"
Post a Comment