我想知道如何检索刚刚使用router.get存储的图像。任何帮助,将不胜感激!任何改善我的代码的技巧也将不胜感激!祝你有美好的一天
profile.js
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.originalname + '-' + Date.now() + '.jpg')
}
});
var upload = multer({ storage: storage, limits:{
fileSize: 1024 * 1024
} }).single('image');
router.post('/', function (req, res) {
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading
}
console.log(req.file)
console.log(req.file.path)
res.json({
success: true,
message: 'Image uploaded!'
});
// Everything went fine
})
});
module.exports = router;
app.js
var express=require('express');
var app=express();
var multer = require('multer');
var bodyParser=require('body-parser');
var urlencodedParser=bodyParser.urlencoded({extended:false});
app.use(bodyParser.json()); //parse appilcation/json data
app.use(urlencodedParser);
app.use('/profile', profile);
module.exports=app;
答案 0 :(得分:0)
您可以在GET路由中使用快速sendFile函数。您应该在上传路径中使用multer
中间件来管理多部分数据。还可以使用path
模块来管理目录路径。(我假设'uploads'目录位于项目的根目录中,而路由则位于'routes'目录中)
var express = require('express');
var router = express.Router();
var multer = require('multer');
var path = require('path');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../uploads/'))
},
filename: function (req, file, cb) {
cb(null, file.originalname + '-' + Date.now() + '.jpg')
}
});
var upload = multer({
storage: storage,
limits: { fileSize: 1024 * 1024 }
});
router.post('/image', upload.single('image'), function (req, res) {
console.log(req.file);
console.log(req.file.path);
res.json({
success: true,
message: 'Image uploaded!',
name: req.file.filename
});
// Everything went fine
});
router.get('/image/:filename', function (req, res) {
res.sendFile(path.join(__dirname, "../uploads/", req.params.filename));
});
module.exports = router;