Created
November 2, 2020 20:28
-
-
Save paulobunga/eaac32a8883b359d1ab6193b31214841 to your computer and use it in GitHub Desktop.
Express JS file upload
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"); | |
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