简体   繁体   中英

How to display uploaded image using multer?

I'm using nodejs as backend and vuejs as front. I've uploaded somes files as test using postman to my backend, but, how could I display these uploaded files using 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. If I try to use it in my img src ( http://localhost:3000/api/company/public/logo-1531296527722 ) it doesn't displayed. If I try to access this route I got this error 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.

I dit it! In my app.js I include 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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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