0

I'm storing images at mongodb database. I want to display response i get from express api as image on client side. Image source looks like this

src="/image/data/5a44dde172aa021d107e7d33"

And i send back data like this. And when i write image url to browser it shows nothing.

var imgId = req.params.id;

imageModel.findById(imgId)
    .then((img) => {
        res.status(200).send(img.data);

    })
    .catch((exc) => {
        res.status(400).send();
    });

And i upload the file like this.

router.post("/", upload.any(), (req, res) => {


    if (req.files && req.files.length > 0) {
        for (var i = 0; i < req.files.length; i++) {
            var file = req.files[i];

            var image = new imageModel({ data: file.buffer.toString(), name: file.fieldname, createdBy: req.user.id });
            image.save(function (err, img) {
                if (err)
                    res.status(400).send(err);
                else
                    res.status(200).send(response.create(img));
            });
        }
    }
});

What am i doing wrong?

3
  • You will need to set content-type Commented Dec 28, 2017 at 14:48
  • What is your img.data type? base64String? BinaryStirng? Commented Dec 29, 2017 at 6:46
  • When i send img.data directly and paste image url to browser it prompts download. But when i call toString() on img.data and set content-type to image/jpeg it displays an image but as a blank square only. @hoangdv It's buffer type of mongoose. I think it stores data as binary. Commented Dec 29, 2017 at 6:46

1 Answer 1

1

I'm solved this by changing

 file.buffer.toString()

to

 file.buffer.toString('binary')

on file upload code and

res.status(200).send(img.data)

to

 res.status(200).contentType("image/jpeg").send(new Buffer(img.data.toString(), 'binary'))

on get api method. It works as i expected, image can be displayed on page now.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.