Skip to content

Instantly share code, notes, and snippets.

@Wildanzr
Last active April 3, 2023 07:38
Show Gist options
  • Save Wildanzr/c7c1ac503b62792caef8ab82c52fb565 to your computer and use it in GitHub Desktop.
Save Wildanzr/c7c1ac503b62792caef8ab82c52fb565 to your computer and use it in GitHub Desktop.
// Create an express app
const PORT = 5000; // Best practice use environment variable
const HOST = "http://localhost"; // Best practice use environment variable
const app = express();
app.use(express.json());
app.post("/uploads", upload.single("file"), (req, res) => {
const file = req.file;
if (!file) {
return res.status(400).json({
message: "File not found!",
});
} else if (!validateFileTypes(file)) {
deleteFile(file);
return res.status(400).json({
message: "Unsupported file format",
});
}
return res.status(200).json({
message: "File uploaded succesfully",
data: {
url: `${HOST}:${PORT}/uploads/${file.filename}`,
},
});
});
app.get("/uploads/:filename", (req, res) => {
const file = req.params.filename;
const filePath = path.join(__dirname, "uploads", file);
if (!fs.existsSync(filePath)) {
return res.status(404).json({
message: "File not found",
});
}
return res.sendFile(filePath);
});
app.listen(PORT, () => {
console.log(`Server run on ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment