无法使用NODE + mongoose + multer从mongooDB检索图像成功上传图像到服务器后,multer将图像数据保存到mongooDB
它是我架构:
const mongoose = require('mongoose');
let Schema = mongoose.Schema;
const imageSchema = new Schema({
name: String,
desc: String,
img:
{
data: Buffer,
contentType: String
}
})
const Image = mongoose.model('Image', imageSchema);
module.exports = Image;
//its my server side
let storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'uploads')
},
filename: (req, file, cb) => {
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.fieldname + '.' + extension)
}
});
let upload = multer({ storage: storage });
app.post('/uploadImage', upload.single('image'),async (req, res, next) => {
let extArray = req.file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
let obj = {
name: '1',
desc: '1',
img: {
data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
contentType: `image/${extension}`,
}
}
await new Image(obj).save().then(image =>{
res.send(image)
})
//its my client side
/*eslint-disable*/
const uploadPicture = () => {
const uploadButton = document.getElementById('add-picture');
const pushImage = (event) => {
let form = new FormData();
form.append('image', event.target.files[0]);
$.ajax({
url: '/uploadImage',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
data: form,
}).then((image) => {
document.getElementById('added-image').src = `data:${image.img.contentType};base64,${image.img.data.toString('base64')}`;
})
}
uploadButton.addEventListener('change', pushImage, false);
}
export {uploadPicture}
});
我上传图像后,图像保存在文件夹'上传'和保存在mongoo enter image description here
但在浏览器中我得到错误数据:图像/jpeg;base64,[对象对象]:1获取数据:图像/jpeg;base64,[对象对象]网络::错误_无效_URL
enter image description here
请帮帮我,我做错了什么?
我尝试改变urlencoded到utf-8,但没有帮助我
1条答案
按热度按时间rhfm7lfc1#
尝试验证您试图访问该图像的位置,并验证您传递来访问它的参数是什么,也许您需要访问从mongodb接收并将其发送到Api端点的对象内的值
参考:数据:image/jpeg;base64,[对象对象]:说明:它不是访问图像本身,而是尝试将对象作为路径传递
希望能有所帮助!