简体   繁体   English

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

[英]How to display uploaded image using multer?

I'm using nodejs as backend and vuejs as front.我使用 nodejs 作为后端,使用 vuejs 作为前端。 I've uploaded somes files as test using postman to my backend, but, how could I display these uploaded files using multer?我已经使用邮递员将一些文件作为测试上传到我的后端,但是,如何使用 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');
});

I got an image named 'logo-1531296527722' in my api public folder.我的 api 公共文件夹中有一个名为“logo-1531296527722”的图像。 If I try to use it in my img src ( http://localhost:3000/api/company/public/logo-1531296527722 ) it doesn't displayed.如果我尝试在我的 img src ( http://localhost:3000/api/company/public/logo-1531296527722 ) 中使用它,它不会显示。 If I try to access this route I got this error Cannot GET /api/company/public/logo-1531296527722 .如果我尝试访问此路由, Cannot GET /api/company/public/logo-1531296527722收到此错误Cannot GET /api/company/public/logo-1531296527722 In all questions about that, nodejs has its own html processor like ejs or jade, but I my case, nodejs is just serving my front and all images must be rendered using vuejs.在所有相关问题中,nodejs 有自己的 html 处理器,如 ejs 或 jade,但我的情况是,nodejs 只是服务于我的前端,所有图像都必须使用 vuejs 呈现。

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

I had the same problem.我有同样的问题。 Change your code from更改您的代码

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

to this:对此:

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

This should do the work :)这应该可以完成工作:)

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

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