Skip to content

Instantly share code, notes, and snippets.

@kyktommy
Last active January 31, 2021 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyktommy/ccbd0b2b8dd00f2ace5e7585bf80fe94 to your computer and use it in GitHub Desktop.
Save kyktommy/ccbd0b2b8dd00f2ace5e7585bf80fe94 to your computer and use it in GitHub Desktop.
expressjs multer file upload
<form action="/photos/upload" enctype="multipart/form-data" method="post">
<input type="file" name="photos" multiple>
<input type="text" name="desc">
<input type="submit" value="Submit">
</form>
const path = require("path");
const express = require("express");
const multer = require("multer");
const upload = multer({
// file size limitation in bytes
limits: {
fileSize: 1 * 1024 * 1024,
},
// file validation
fileFilter: (req, file, cb) => {
const ext = path.extname(file.originalname);
if (ext !== ".jpg") {
cb(new Error("image must be jpg"));
}
cb(null, true);
},
// file storage configuration
storage: multer.diskStorage({
destination: (req, file, cb) => {
cb(null, path.join(__dirname, "/uploads"));
},
filename: (req, file, cb) => {
let filename =
file.fieldname + "-" + Date.now() + path.extname(file.originalname);
cb(null, filename);
},
}),
});
const uploadTwo = upload.array("photos", 2);
const app = express();
app.post("/photos/upload", function (req, res, next) {
uploadTwo(req, res, (err) => {
// file size multer error
if (err instanceof multer.MulterError) {
return res.end("multer: " + err);
}
// custom error from fileFilter
else if (err) {
return res.end("err: " + err);
}
// upload.single
// console.log(req.file);
// upload.fields
// console.log(req.files['first'][0])
// upload.files
console.log(req.files);
// other form data
console.log(req.body);
return res.end("ok");
});
});
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "/index.html"));
});
app.listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment