IN NODE JS
const express = require("express");
const multer = require("multer");
const app = express();
app.use(express.static("./public"));
const fs = require("fs");
const Storage = multer.diskStorage({
destination: (req, file, callback) => {
if (!fs.existsSync("./public/uploads")) {
fs.mkdirSync("./public/uploads");
}
callback(null, "./public/uploads");
},
filename: (req, file, callback) => {
callback(
null,
file.fieldname +
"_" +
Date.now() +
"_" +
file.originalname.replace(/\s/g, "_")
);
},
});
const upload = multer({
storage: Storage,
});
app.post("/insert", upload.any(), function (req, res) {
try {
if (req.files) {
let uploaded_file = req.files[0].filename;
console.log(uploaded_file);
res.redirect(`/see/${uploaded_file}`);
}
} catch (e) {
throw e;
}
});
app.get("/see/:name", function (req, res) {
res.send(`
<a href="/"><input type="button" value="Go Back""/></a>
<br/>
<br/>
<img src="/uploads/${req.params.name}" alt="Girl in a jacket" width="500" height="600">
`);
});
app.get("/", function (req, res) {
res.send(`
<div style="margin:100px">
<form action="/insert" enctype="multipart/form-data" method="post">
<div class="form-group">
<input type="file" class="form-control-file" name="uploaded_file">
<input type="submit" value="Get me the stats!" class="btn btn-default">
</div>
</form>
</div>
`);
});
app.listen(3000, () => {
console.log(`App running at http://localhost:3000`);
});
- One can upload a video also, Then the image view changes to a video view in see/:name then we use an HTML tag to view the video.
- To serve static files such as images, CSS files, and JavaScript files, use the express.static() built-in middleware function in Express.
- The fs.mkdirSync() method is used to create a directory Synchronously.
Comments
Post a Comment