问题
I am working on patient photo upload using express, mongodb, multer, ejs, and croppiejs. When user uploads a photo they have an option to crop it. I am saving the cropped photo in a collection as BLOB object in a field called croppedPhoto.
Now, i want to display that cropped photo on front-end. I am passing the patients object (which contains all the data fields of a record including cropped photo).
I am thinking of converting that blob object to base64 and display it. But the issue is I am not sure how to use croppedPhoto field value in ejs template to convert it.
server.js [Finding all patients and passing in to ejs template - includes croppedPhoto field as well]
app.get('/', async (req, res) => {
const patients = await Patient.find();
res.render('index', { patients: patients });
});
index.ejs [want to display the photo in img tag]
<div class="flex flex-wrap mt-10">
<% patients.forEach(patient => { %>
<div
class="flex flex-col items-center justify-center h-auto lg:h-auto lg:w-32 flex-none bg-cover rounded-t lg:rounded-t-none lg:rounded-l text-center overflow-hidden">
<img src="<%= patient.croppedPhoto %>" class="my-3 w-20 h-20 rounded-full" alt="Patient Photo">
</div>
<% }) %>
</div>
Thanks!!
回答1:
Usually and when it comes to uploading files to the server, you have to avoid saving the file itself in the database, instead, you can move the file from the client's desktop to the directory you want (your application images folder where you store the images) using Express file upload , and you save the path
of that file in the database, normally it would be something like this : /images/test.png
.
Here is an example :
router.route('/add').post(function (req, res) {
if (req.files && req.body.name) {
var file = req.files.file
// to move the file to the direct i want !
file.mv("client/public/img/client/categories/" + file.name, err => {
if (err) {
console.error(err);
return res.status(500).send(err);
}
});
var newCategorie = new Categorie({
name: req.body.name,
imgUrl: "/img/client/categories/" + file.name // TO SAVE THE PATH
});
}
newCategorie
.save()
.then(categories => res.json(categories))
.catch(err => res.status(400).json('Error: ' + err));
} else {
res.status(400).json({ msg: "Please enter all fields" });
}
});
Then in your EJS template, it would be very easy to access the src of the image : <img src="OBJECT.ImgURL" />
来源:https://stackoverflow.com/questions/61536943/how-to-convert-blob-object-in-ejs-template