我已使用multer
和disk storage
来上传图片
在项目文件夹中,我只有文件名
即
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);
}
})
});
compnent.ts
ngOnInit() {
this.route.paramMap.pipe(
switchMap((params: ParamMap) =>
this.videoService.editVideo(params.get('id')))).subscribe(res=>{this.video=res});
}
component.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'
答案 0 :(得分:2)
我认为您的图像已保存在图像文件夹中,但是您尝试直接在根文件夹中访问该图像。尝试将images/
添加为。图像路径的前缀,它应该可以工作。
尝试:
<img [src]="'images/'+video.file.filename | safe" alt="not found" width="100px" height="150px">