node.js multer上传后无法显示图像

node.js multer上传后无法显示图像,node.js,express,ejs,multer,Node.js,Express,Ejs,Multer,我有一个非常简单的表单,用于将图像文件上载到服务器的文件系统,并在页面上呈现图像。显然,我可以按预期上传图像,但无法渲染图像。我得到一个损坏的图像图标和 当我打开图像位置时,我无法get/uploads/undefined下面分别是我的代码app.js和index.ejs const express = require('express'); const multer = require('multer'); const ejs = require('ejs'); const path = re

我有一个非常简单的表单,用于将图像文件上载到服务器的文件系统,并在页面上呈现图像。显然,我可以按预期上传图像,但无法渲染图像。我得到一个损坏的图像图标和 当我打开图像位置时,我无法
get/uploads/undefined
下面分别是我的代码app.js和index.ejs

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))
我的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>

图片上传演示
图像上传
文件
提交

“class=”img responsive“>
你太接近了!你刚刚输入了一个输入错误-
req.file.filname
应该是上传处理程序中的
req.file.filename