Skip to content

Instantly share code, notes, and snippets.

@paulobunga
Created November 2, 2020 20:28
Show Gist options
  • Save paulobunga/eaac32a8883b359d1ab6193b31214841 to your computer and use it in GitHub Desktop.
Save paulobunga/eaac32a8883b359d1ab6193b31214841 to your computer and use it in GitHub Desktop.
Express JS file upload
const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const port = process.env.PORT || 3000;
const app = express();
const upload = multer({
dest: "./uploads",
});
app.post("/upload", upload.single("file"), (req, res) => {
const tempPath = req.file.path;
const targetPath = path.join(__dirname, `./uploads/${req.file.originalname}`);
if (path.extname(req.file.originalname).toLowerCase() === ".png") {
fs.rename(tempPath, targetPath, (err) => {
if (err) {
return res.status(500).json({ error: err });
}
res.status(200).contentType("text/plain").end("File uploaded!");
});
} else {
fs.unlink(tempPath, (err) => {
if (err) {
return res.status(500).json({ error: err });
}
res
.status(403)
.contentType("text/plain")
.end("Only .png files are allowed!");
});
}
});
app.listen(port, () => console.log("WORKING"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment