Created
March 2, 2020 05:56
-
-
Save heytulsiprasad/9ef9ec77be42bbd52bab117a2f2a565d to your computer and use it in GitHub Desktop.
adding all the functionality to package multer for image uploading
This file contains 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 multer = require("multer") | |
const express = require("express") | |
const app = express() | |
const storage = multer.diskStorage({ | |
destination: function (req, file, cb) { | |
cb(null, __dirname + "/uploads") | |
}, | |
filename: function (req, file, cb) { | |
const firstname = file.originalname.split(".")[0] | |
const lastname = file.originalname.split(".")[1] | |
const newname = firstname + `anything-here` + lastname | |
cb(null, newname) | |
} | |
}) | |
const upload = multer({ | |
storage, | |
limits: { | |
fileSize: 1000000 // in kbs | |
}, | |
fileFilter(req, file, cb) { | |
if (!file.originalname.match(/\.(doc|docx)$/)) { | |
return cb(new Error("Please upload a valid word document")) | |
} | |
cb(undefined, true) | |
} | |
}) | |
app.post("/users/upload", upload.single("upload"), (req, res) => { | |
res.send() | |
}, (error, req, res, next) => { | |
res.status(400).send({ error: error.message }) | |
}) | |
app.listen(3000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment