retrieve an image from mongodb and display it using angular7

Viewed 1425

i have uploaded image using multer with disk storage

in project folder i have only filename

i.e

filename: "1561256874022.jpg"

while from mongo i am getting this object

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 post request

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 get request

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">

Getting response from api but in browser i have this error

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'
1 Answers

I think your image is getting saved in images folder, but you are trying to access the image directly in the root folder. Try adding images/ as . aprefix to your image path, and it should work.

Try :

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