Rest Api - Upload Video File to Database Js
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 eight Client / Angular 10 Client / Angular 11 Client / Angular 12
– Angular Material 12
– Vue Client / Vuetify Customer
– React Customer / React Hooks Client
– Material UI Customer
– Axios Customer
Related Posts:
– Google Cloud Storage with Node.js: File Upload example
– How to upload multiple files in Node.js
– Upload/shop images in MySQL using Node.js, Limited & 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 Rest APIs for uploading Files
Our Node.js Application volition provide APIs for:
- uploading File to a static binder in the Server (restrict file size: 2MB)
- downloading File from server with the link
- getting list of Files' information (file name & url)
This is the static folder that stores all uploaded files:
If we get list of files, the Node.js Rest Apis will return:
Each item in the response array has a url that you can use for downloading the file.
These are APIs to be exported:
Methods | Urls | Deportment |
---|---|---|
POST | /upload | upload a File |
Go | /files | get List of Files (name & url) |
GET | /files/[filename] | download a File |
Technology
- limited four.17.1
- multer 1.4.2
- cors two.8.v
Projection Structure
This is the project directory that nosotros're gonna build:
– resources/static/assets/uploads
: folder for storing uploaded files.
– middleware/upload.js
: initializes Multer Storage engine and defines middleware function to salve uploaded files in uploads
folder.
– file.controller.js
exports Rest APIs: Mail service a file, Go all files' information, download a File with url.
– routes/alphabetize.js
: defines routes for endpoints that is called from HTTP Client, use controller to handle requests.
– server.js
: initializes routes, runs Express app.
Setup Node.js Express File Upload project
Open control prompt, change electric current directory to the root folder of our project.
Install Limited, Multer, CORS modules with the following command:
npm install express multer cors
The bundle.json file will expect like this:
{ "proper noun": "node-js-express-upload-download-files", "version": "ane.0.0", "clarification": "Node.js Express Residuum APis to Upload/Download Files", "chief": "server.js", "scripts": { "test": "echo \"Error: no test specified\" && exit i" }, "keywords": [ "node js", "upload", "download", "file", "multipart", "rest api", "express" ], "author": "bezkoder", "license": "ISC", "dependencies": { "cors": "^2.8.five", "express": "^4.17.1", "multer": "^1.4.two" } }
Create middleware for file upload
The middleware volition utilise Multer for handling multipart/form-data along with uploading files.
Inside middleware binder, create upload.js file:
const util = require("util"); const multer = require("multer"); const maxSize = ii * 1024 * 1024; allow storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, __basedir + "/resources/static/avails/uploads/"); }, filename: (req, file, cb) => { panel.log(file.originalname); cb(null, file.originalname); }, }); allow uploadFile = multer({ storage: storage, limits: { fileSize: maxSize }, }).single("file"); let uploadFileMiddleware = util.promisify(uploadFile); module.exports = uploadFileMiddleware;
In the lawmaking above, we've done these steps:
– Commencement, we import multer
module.
– Next, we configure multer
to use Disk Storage engine.
You can see that we take ii options here:
– destination
determines binder to shop the uploaded files.
– filename
determines the name of the file inside the destination
folder.
util.promisify()
makes the exported middleware object tin can be used with async-expect
.
Restrict file size with Multer
With the new multer
API. We tin can add limits: { fileSize: maxSize }
to the object passed to multer()
to restrict file size.
allow storage = multer.diskStorage(...); const maxSize = two * 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 part for file upload
- catch Multer error (in middleware function)
- return response with message
– For File Information and Download:
-
getListFiles()
: read all files in uploads binder, return list of files' information (proper noun, url) -
download()
: receives file name as input parameter, so uses Express res.download API to transfer the file at path (directory + file name) every bit an 'attachment'.
const uploadFile = require("../middleware/upload"); const upload = async (req, res) => { attempt { await uploadFile(req, res); if (req.file == undefined) { return res.condition(400).transport({ bulletin: "Please upload a file!" }); } res.status(200).send({ message: "Uploaded the file successfully: " + req.file.originalname, }); } catch (err) { res.status(500).send({ message: `Could not upload the file: ${req.file.originalname}. ${err}`, }); } }; const getListFiles = (req, res) => { const directoryPath = __basedir + "/resources/static/assets/uploads/"; fs.readdir(directoryPath, part (err, files) { if (err) { res.status(500).ship({ message: "Unable to scan files!", }); } let fileInfos = []; files.forEach((file) => { fileInfos.button({ name: file, url: baseUrl + file, }); }); res.status(200).transport(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.status(500).ship({ message: "Could not download the file. " + err, }); } }); }; module.exports = { upload, getListFiles, download, };
– Nosotros call middleware function uploadFile()
showtime.
– If the HTTP request doesn't include a file, send 400
condition in the response.
– We likewise catch the mistake and send 500
status with fault message.
And then, how to handle the case in that user uploads the file exceeding size limitation?
Handle Multer file size limit error
Nosotros can handle the error by checking error lawmaking (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.condition(500).ship({ message: "File size cannot be larger than 2MB!", }); } res.status(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 make up one's mind how the server will response by setting up the routes.
At that place are 3 routes with respective controller methods:
- Mail
/upload
:upload()
- Go
/files
:getListFiles()
- Go
/files/[fileName]
:download()
Create index.js file inside routes folder with content like this:
const limited = require("express"); const router = express.Router(); const controller = require("../controller/file.controller"); let routes = (app) => { router.post("/upload", controller.upload); router.go("/files", controller.getListFiles); router.become("/files/:name", controller.download); app.use(router); }; module.exports = routes;
You can see 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 = crave("limited"); const app = limited(); global.__basedir = __dirname; var corsOptions = { origin: "http://localhost:8081" }; app.use(cors(corsOptions)); const initRoutes = require("./src/routes"); app.use(express.urlencoded({ extended: truthful })); initRoutes(app); allow 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 Remainder apis
- cors provides Express middleware to enable CORS with various options.
– create an Limited app, so add cors
middlewares using app.employ()
method. Notice that nosotros set origin: http://localhost:8081
.
– listen on port 8080 for incoming requests.
Run & Examination
Get-go we need to create uploads binder with the path resources/static/assets
.
On the project root folder, run this command: node server.js
.
Let's use Postman to make HTTP Mail service request with a file.
– Upload a file with size larger than max file size (2MB):
– Check uploads binder later on uploading several files:
– Retrieve list of Files' data:
– Now you lot can download any file from ane of the paths above.
For example: http://localhost:8080/files/bezkoder.png
.
Decision
Today we've learned how to create Node.js Express Residuum API to upload file into static folder using Multer for middleware handling multipart file. Yous also know how to restrict file size and take hold of Multer file size limit fault.
Post-obit tutorials explain how to build Front-terminate Apps to work with our Node.js Limited Server:
– Angular eight Client / Athwart 10 Customer / Angular xi Customer / Angular 12
– Angular Cloth 12
– Vue Client / Vuetify Client
– React Client / React Hooks Customer
– Fabric UI Client
– React Paradigm Upload with Preview
– Axios Client
For multiple Files at once:
How to upload multiple files in Node.js
Upload to GCS:
Google Deject Storage with Node.js: File Upload example
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 information into Database
If you want to upload images into database, yous can find instructions at:
– Upload/store images in MySQL using Node.js, Limited & Multer
– How to upload/store images in MongoDB using Node.js, Express & Multer
Happy Learning! See you again.
Further 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/
Post a Comment for "Rest Api - Upload Video File to Database Js"