繁体   English   中英

如何使用multer显示上传的图像?

[英]How to display uploaded image using multer?

我使用 nodejs 作为后端,使用 vuejs 作为前端。 我已经使用邮递员将一些文件作为测试上传到我的后端,但是,如何使用 multer 显示这些上传的文件?

const multer = require('multer');


const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/')
    },
    filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
    }
})

const upload = multer({ storage: storage }).single('logo');

router.post('/logo', auth.authorize, (req, res, next) => {
    upload(req, res, (err) => {
    });
    res.status(200).send('uploaded');
});

我的 api 公共文件夹中有一个名为“logo-1531296527722”的图像。 如果我尝试在我的 img src ( http://localhost:3000/api/company/public/logo-1531296527722 ) 中使用它,它不会显示。 如果我尝试访问此路由, Cannot GET /api/company/public/logo-1531296527722收到此错误Cannot GET /api/company/public/logo-1531296527722 在所有相关问题中,nodejs 有自己的 html 处理器,如 ejs 或 jade,但我的情况是,nodejs 只是服务于我的前端,所有图像都必须使用 vuejs 呈现。

我搞定了! 在我的 app.js 中,我包含app.use('/dist', express.static(path.join(__dirname + '/dist')));

我有同样的问题。 更改您的代码

filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now())
}

对此:

filename: function (req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
    }

这应该可以完成工作:)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM