gpt4 book ai didi

node.js - 从 mongodb 检索图像并使用 angular7 显示它

转载 作者:可可西里 更新时间:2023-11-01 10:08:21 26 4
gpt4 key购买 nike

我已经使用 multer磁盘存储上传了图片

在项目文件夹中我只有文件名

filename: "1561256874022.jpg"

当我从 mongo 得到这个对象时

destination: "C:\Users\Me\Desktop\project\testing\server\routes/src/assets/images"

encoding: "7bit"

fieldname: "file"

filename: "1561256874022.jpg"

mimetype: "image/jpeg"

originalname: "new.jpg"

path: "C:\Users\Me\Desktop\project\testing\server\routes\src\assets\images\1561256874022.jpg"

size: 1256070

__proto__:Object

API 发布请求

var storage = multer.diskStorage({
destination: function (req, file, cb) {//destination where images will store
cb(null, __dirname + '/src/assets/images')
},
filename: function (req, file, callback) {
callback(null, Date.now() + path.extname(file.originalname));
}
})
//configuration
const upload = multer({
storage: storage,
})

//post data
router.post('/image', upload.single('file'), async (req, res) => {
try {
var newImage = new Image();
newImage.file = req.file;
newImage.description = req.body.description;
await newImage.save();
res.status(200).send(newImage);
}
catch (e) {
console.log("failed " + e);
}
})

API 获取请求

router.get('/image/:id', (req, res) => {
Image.findById(req.params.id)
.exec(function (err, data) {
if (err) {
console.log('error');
}
else {
console.log("image returned "+data)
res.json(data);
}
})

});

组件.ts

ngOnInit() {    

this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
this.videoService.editVideo(params.get('id')))).subscribe(res=>{this.video=res});
}

组件.html

 <img [src]="video.file.filename | safe" alt="not found" width="100px" height="150px">

从 api 获取响应,但在浏览器中出现此错误

core.js:15714 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: '1561256874022.jpg' Error: Cannot match any routes. URL Segment: '1561256874022.jpg'

最佳答案

我认为您的图像已保存在图像文件夹中,但您正试图直接在根文件夹中访问图像。尝试将 images/ 添加为 .图像路径的前缀,它应该可以工作。

尝试:

<img [src]="'images/'+video.file.filename | safe" alt="not found" width="100px" height="150px">

关于node.js - 从 mongodb 检索图像并使用 angular7 显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56786535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com