Node.js 如何将图像文件作为对节点的响应发送
我尝试使用multer上传图像,并成功地将图像上传到名为images的后端文件夹中,当从angular frontend上传时,所有图像都存储在该文件夹中。 但我还想在调用api时将图像作为响应发送回一些json()数据 这是我上传图片的代码:Node.js 如何将图像文件作为对节点的响应发送,node.js,angular,express,Node.js,Angular,Express,我尝试使用multer上传图像,并成功地将图像上传到名为images的后端文件夹中,当从angular frontend上传时,所有图像都存储在该文件夹中。 但我还想在调用api时将图像作为响应发送回一些json()数据 这是我上传图片的代码: /* app.js */ const fileStorage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'images'); }, fi
/* app.js */
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'images');
},
filename: (req, file, cb) => {
console.log(file)
console.log('filename =',file.filename)
cb(null, uuidv4() + '-' + file.originalname);
}
});
const fileFilter = (req, file, cb) => {
if (
file.mimetype === 'image/png' ||
file.mimetype === 'image/jpg' ||
file.mimetype === 'image/jpeg'
) {
cb(null, true);
} else {
cb(null, false);
}
};
app.use(
multer({ storage: fileStorage, fileFilter: fileFilter }).single('image')
);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/images', express.static(path.join(__dirname, 'images')));
上面的代码是上传图片的。我想知道如何创建一个api来获取图像以及其他数据,如标题、描述、价格
/* controller */
exports.postAddProduct = (req, res, next) => {
const title = req.body.title;
const image = req.file;
const price = req.body.price;
const description = req.body.description;
Admin.findById(req.adminId)
.then(admin=>{
if(!admin){
return res.redirect('/')
}
if(req.adminId !== admin._id.toString() ) {
return res.redirect('/')
}
if (!image) {
console.log('not found image')
return res.status(422).json('Attached file is not an image.')
}
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log(errors.array());
return res.status(422).json(errors.array()[0].msg,)
}
const imageUrl = image.path;
const product = new Product({
title: title,
price: price,
description: description,
imageUrl: imageUrl,
userId: req.adminId
});
product
.save()
.then(result => {
console.log('Created Product');
return res.status(201).json(result)
})
})
.catch(err => {
console.log(err)
const error = new Error(err);
error.httpStatusCode = 500;
return next(error);
});
};