In a Node.js application, if there is a requirement to upload files to the server Multer is a good option. It can be used in any JavaScript backend. For this article, we will use Express.
Multer is a Node.js middleware for handling multipart/form-data
Ways to use Multer:
There are multiple ways to use Multer:
1. We upload files directly to the Node server (in a server)
2. Saving file data or base64 data in a database
3. Save AWS S3 bucket to save and manage files (using a service)
In this article, we will save files directly to the server.
Setting up Express application:
→ We need to install the basic express setup using the below command
express <your_app_name> --view=ejs
→ Run the below command in the express root directory for installing Multer:
npm i multer
STEP1: Create Routes:
We can upload a single file as well as multiple files.
var express = require("express");
var router = express.Router();const upload = require("../common");/* GET home page. */
router.get("/", function (req, res, next) {
res.render("index", { title: "Express" });
});// Single file Upload - image key should be passed postmanrouter.post("/single", upload.single("image"), (req, res, next) => {
console.log(req.file); // UPLOADED FILE DESCRIPTION RECEIVED
res.send("uploaded successfully");
});// Multiple files Upload - images key should be passed in postmanrouter.post("/multiple", upload.array("images"), (req, res) => {
console.log(req.files); // UPLOADED FILE DESCRIPTION RECEIVED
res.send({
status: "success",
message: "Files uploaded successfully",
data: req.files,
});
});module.exports = router;
common.js (Handling upload functionality)
→ Here we write the logic for uploading files
const multer = require("multer");
var fs = require("fs");var dir = "./public/images/nov"; // PATH TO UPLOAD FILE
if (!fs.existsSync(dir)) { // CREATE DIRECTORY IF NOT FOUND
fs.mkdirSync(dir, { recursive: true });
}const fileStorageEngine = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, dir);
},
filename: (req, file, cb) => {
cb(null, Date.now() + "-" + file.originalname);
},
});const upload = multer({ storage: fileStorageEngine });module.exports = upload;
→ Run the Node server using the below command
npm start
→ We will use Postman for importing files. You can follow below screenshots and videos for Postman
Route: http://localhost:5000/single
Type: POST
Body: form-data, select key as image of type File
→ We get the file name and path where the file is saved. Let us now go to the below path in our codebase.
→ We have successfully uploaded the file
→ Let us now do multiple uploads using our second route:
Route: http://localhost:5000/multiple
Type: POST
Body: form-data, select key as images of type File
→ We get an array of images along with filename and path
→ Let us check the file in the codebase
Video:
Repository:
https://github.com/AmirMustafa/export-to-excel
Closing Thoughts:
We have learnt how we can upload files directly in Node.js. We can also upload files in the AWS S3 bucket and upload base 64 data in the database.
Thank you for being till the end 🙌 . If you enjoyed this article or learned something new, support me by clicking the share button below to reach more people and/or give me a follow on Twitter to see some other tips, articles, and things I learn and share there.
'Study > Node.js' 카테고리의 다른 글
이더리움 웹앱 만드는 방법 (0) | 2021.11.12 |
---|---|
PayPI를 사용하여 NodeJS로 수익창출 하는 방법 (0) | 2021.11.12 |
Node.js로 웹 스크랩핑 해보기 (0) | 2021.11.11 |
[NodeJS] NodeJs 모듈 업데이트 하는 방법 | Package.json의 종속성을 업데이트 해보자. (0) | 2021.07.25 |
[NodeJS] NodeJs + Express.js + MySQL CRUD 연동 (0) | 2021.06.19 |