I have created a simple node solution which contains a form and on that submit the form it will display the image that is being inserted in the form.
app.js
const app = express()
app.use(express.static('public'))
app.engine('hbs',handlebars({
layoutsDir : __dirname + '/views/layouts',
defaultLayout : "mainlayout",
extname : "hbs",
partialsDir : __dirname + '/views/partials'
}))
app.use("/uploader", imgUploader)
app.set('view engine','hbs')
impUpload.js
const express = require('express')
const route = express.Router();
const multer = require('multer');
const path = require('path');
const Storage = multer.diskStorage({
destination: './public/uploads',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
const upload = multer({
storage: Storage,
fileFilter: function (req, file, cb) {
checkFileType(file, cb);
}
}).single('myImage');
function checkFileType(file, cb) {
const filetypes = /jpeg|jpg|png|gif/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase())
const mimeType = filetypes.test(file.mimetype);
if (extname && mimeType) {
return cb(null, true)
}
else {
cb('Error: Images Only!!!');
}
}
route.get("/", (req, res) => {
console.log("inside imgupload folder")
res.render("fileUpload")
})
route.post("/uploaded", (req, res) => {
upload(req, res, (error) => {
if (error) {
res.render("fileUpload", { message: error })
}
else {
if (req.file == undefined) {
res.render("fileUpload", { message: 'Please upload a file' })
}
else {
res.render('fileUpload', {
message: 'File Uploaded Successfully',
file: `uploads/${req.file.filename}`
});
}
}
})
})
module.exports = route
fileUpload.js
<div class="container">
<h1>file upload</h1>
{{message}}
<form action="/uploader/uploaded" method="post" enctype="multipart/form-data">
<div class="file-field input-field">
<div class="btn">
<span>File</span>
<input name="myImage" type="file">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
<button type="submit" class="btn n">Submit</button>
</form>
<br>
</div>
<div>
{{#if file}}
<img src="{{file}}" class="responsive-img">
{{/if}}
</div>
Currently, my solution is structured as below
I am getting the error in the console
GET http://localhost:3000/uploader/uploads/myImage-1589223958713.PNG 404 (Not Found)
I am not getting why it's trying to find that img in the uploader/uploads although I have defined public folder in the app.js
But when trying the same code in the app.js it's working absolutely fine.
also if I try express().use(express.static(path.join(__dirname , '../public'))) in the imgupload.js then i am getting the error
Not allowed to load local resource: file:///C:/arunoday/node/login_express_mongo/public/uploads/myImage-1589220613014.PNG
any help would be appreciated.
See Question&Answers more detail:
os