get name of file in js uploading

In this tutorial, I will bear witness 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 / Athwart xi Client / Angular 12
– Angular Material 12
– Vue Client / Vuetify Client
– React Client / React Hooks Client
– Cloth UI Client
– Axios Client

Related Posts:
– Google Deject Storage with Node.js: File Upload instance
– How to upload multiple files in Node.js
– Upload/store images in MySQL using Node.js, Express & Multer
– How to upload/shop images in MongoDB using Node.js, Express & Multer
– Node.js Remainder 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 folder 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:

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

If we get list of files, the Node.js Remainder Apis will return:

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

Each particular in the response array has a url that you can use for downloading the file.

These are APIs to be exported:

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

Technology

  • express iv.17.i
  • multer ane.4.2
  • cors 2.viii.five

Project Construction

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

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

resources/static/assets/uploads: folder for storing uploaded files.
middleware/upload.js: initializes Multer Storage engine and defines middleware role to salve uploaded files in uploads folder.
file.controller.js exports Residuum APIs: Postal service a file, GET all files' information, download a File with url.
routes/index.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 up control prompt, modify current directory to the root folder of our projection.
Install Express, Multer, CORS modules with the following command:

          npm install limited multer cors                  

The parcel.json file volition look like this:

          {   "name": "node-js-limited-upload-download-files",   "version": "1.0.0",   "description": "Node.js Limited Rest APis to Upload/Download Files",   "main": "server.js",   "scripts": {     "test": "repeat \"Error: no test specified\" && exit 1"   },   "keywords": [     "node js",     "upload",     "download",     "file",     "multipart",     "rest api",     "express"   ],   "author": "bezkoder",   "license": "ISC",   "dependencies": {     "cors": "^ii.8.5",     "express": "^4.17.1",     "multer": "^1.4.ii"   } }                  

Create middleware for file upload

The middleware will use Multer for handling multipart/form-information forth with uploading files.

Inside middleware folder, create upload.js file:

          const util = crave("util"); const multer = require("multer"); const maxSize = 2 * 1024 * 1024; let storage = multer.diskStorage({   destination: (req, file, cb) => {     cb(null, __basedir + "/resources/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 lawmaking above, we've done these steps:
– Start, nosotros import multer module.
– Side by side, nosotros configure multer to use Disk Storage engine.

You can see that we have two options hither:
destination determines folder to store the uploaded files.
filename determines the proper noun of the file inside the destination binder.

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

Restrict file size with Multer

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

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

Create Controller for file upload/download

In controller folder, create file.controller.js:

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

  • utilize middleware function for file upload
  • grab Multer error (in middleware part)
  • render response with message

– For File Information and Download:

  • getListFiles(): read all files in uploads folder, return list of files' information (name, url)
  • download(): receives file name as input parameter, then 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) => {   attempt {     look uploadFile(req, res);     if (req.file == undefined) {       return res.condition(400).send({ message: "Please upload a file!" });     }     res.status(200).send({       bulletin: "Uploaded the file successfully: " + req.file.originalname,     });   } catch (err) {     res.status(500).send({       message: `Could non upload the file: ${req.file.originalname}. ${err}`,     });   } }; const getListFiles = (req, res) => {   const directoryPath = __basedir + "/resources/static/avails/uploads/";   fs.readdir(directoryPath, office (err, files) {     if (err) {       res.condition(500).send({         message: "Unable to browse files!",       });     }     let fileInfos = [];     files.forEach((file) => {       fileInfos.push({         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, };                  

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

And so, 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) => {   endeavour {     await uploadFile(req, res);     ...   } grab (err) {     if (err.code == "LIMIT_FILE_SIZE") {       return res.status(500).transport({         message: "File size cannot be larger than 2MB!",       });     }     res.condition(500).send({       message: `Could non upload the file: ${req.file.originalname}. ${err}`,     });   } };                  

Define Route for uploading file

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

At that place 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 similar this:

          const express = 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.get("/files/:name", controller.download);   app.utilise(router); }; module.exports = routes;                  

You tin can encounter that we use controller from file.controller.js.

Create Express app server

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

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

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

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

– create an Express app, and so add cors middlewares using app.employ() method. Notice that we prepare origin: http://localhost:8081.
– listen on port 8080 for incoming requests.

Run & Test

First we need to create uploads folder with the path resources/static/avails.
On the project root binder, run this control: node server.js.

Let's utilise Postman to make 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

– Check uploads folder later on uploading several files:

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

– Recollect list of Files' information:

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

– Now you lot tin download any file from one of the paths above.
For example: http://localhost:8080/files/bezkoder.png.

Decision

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

Following tutorials explicate how to build Forepart-finish Apps to work with our Node.js Limited Server:
– Angular viii Customer / Angular 10 Client / Angular 11 Client / Athwart 12
– Angular Material 12
– Vue Customer / Vuetify Client
– React Customer / React Hooks Client
– Material 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 Cloud Storage with Node.js: File Upload example

You tin too 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, y'all can discover instructions at:
– Upload/shop images in MySQL using Node.js, Express & Multer
– How to upload/shop images in MongoDB using Node.js, Express & Multer

Happy Learning! See y'all once again.

Further Reading

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

Source Code

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

livingstonloness.blogspot.com

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

0 Response to "get name of file in js uploading"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel