Reputation: 386
I have a very simple form that is used to upload image file on the server's file system and render the image on the page. Apparent I can upload the image as expected but fail's to render the image. I get a broken image icon and
when I open the image location I get can't GET /uploads/undefined
below is my code app.js, and index.ejs respectively
const express = require('express');
const multer = require('multer');
const ejs = require('ejs');
const path = require('path');
const port = 3000;
// Init app
const app = express()
// Set storage engine
const storage = multer.diskStorage({
destination: './public/uploads',
filename: function (req, file, cb) {
// null as first argument means no error
cb(null, Date.now() + '-' + file.originalname )
}
})
// Init upload
const upload = multer({
storage: storage,
limits: {
fileSize: 1000000
},
fileFilter: function (req, file, cb) {
sanitizeFile(file, cb);
}
}).single('files')
// Set view engine
app.set('view engine', 'ejs')
// Set static folder
app.use(express.static('./public'));
// Set the initial route
app.get('/', (req, res) => {
res.render('index');
})
// Handle the upload route
app.post('/upload', (req, res) => {
// res.send('done');
upload(req, res, (err) => {
if (err){
res.render('index', { msg: err})
}else{
// If file is not selected
if (req.file == undefined) {
res.render('index', { msg: 'No file selected!' })
}
else{
res.render('index', {
msg: 'File uploaded successfully!',
file: `uploads/${req.file.filname}`
});
}
}
})
})
function sanitizeFile(file, cb) {
// Define the allowed extension
let fileExts = ['png', 'jpg', 'jpeg', 'gif']
// Check allowed extensions
let isAllowedExt = fileExts.includes(file.originalname.split('.')[1].toLowerCase());
// Mime type must be an image
let isAllowedMimeType = file.mimetype.startsWith("image/")
if (isAllowedExt && isAllowedMimeType) {
return cb(null, true) // no errors
}
else {
// pass error msg to callback, which can be displaye in frontend
cb('Error: File type not allowed!')
}
}
app.listen(port, () => console.log('Server started at port : ' + port))
my index.ejs
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<title>Image Upload Demo</title>
</head>
<body>
<div class="container">
<h1>Image Upload</h1>
<%= typeof msg != 'undefined' ? msg : '' %>
<form method="POST" action="/upload" enctype="multipart/form-data">
<div class="file-field input-field">
<div class="btn grey">
<span>File</span>
<input name="files" type="file">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text">
</div>
</div>
<button type="submit" class="btn">Submit</button>
</form>
<br>
<img src="<%= typeof file != 'undefined' ? file : '' %>"class="img-responsive">
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>
</html>
Upvotes: 1
Views: 2995
Reputation: 395
You were so close! You just made a typo - req.file.filname
should be req.file.filename
in your upload handler.
Upvotes: 1