Last active
November 23, 2022 13:40
-
-
Save mortezasabihi/33a0bf68856fd923e4fa2670563403fd to your computer and use it in GitHub Desktop.
NodeJS File Upload rest Api Using multer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require("express"); | |
const multer = require("multer"); | |
const fs = require("fs"); | |
// constant | |
const app = express(); | |
const storage = multer.diskStorage({ | |
destination: (req, file, callback) => { | |
const dir = "uploads/"; | |
!fs.existsSync(dir) && fs.mkdirSync(dir); | |
callback(null, "uploads/"); | |
}, | |
filename: (req, file, callback) => { | |
const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9); | |
let ext = file.originalname.lastIndexOf("."); | |
ext = file.originalname.substr(ext + 1); | |
callback(null, `${file.fieldname}-${uniqueSuffix}.${ext}`); | |
}, | |
}); | |
const upload = multer({ storage }); | |
// middleware | |
app.use(express.json()); | |
// routes | |
app.post("/upload/single", upload.single("file"), (req, res) => { | |
res.json({ file: req.file }); | |
}); | |
app.post("/upload/multiple", upload.array("file", 4), (req, res) => { | |
res.json({ files: req.files }); | |
}); | |
app.listen(5000, () => console.log("App is running on http://localhost:5000")); |
very helpful, but i need to insert the uploaded file into database
Storing files in a database is not a standard and safe way. You should insert the file path into the database and store the file on the server.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
very helpful, but i need to insert the uploaded file into database