【问题标题】:How to convert blob object in EJS Template如何在 EJS 模板中转换 blob 对象
【发布时间】:2020-08-15 14:46:57
【问题描述】:

我正在使用 express、mongodb、multer、ejs 和croppiejs 上传患者照片。当用户上传照片时,他们可以选择裁剪它。我将裁剪的照片保存为名为 croppedPhoto 的字段中的 BLOB 对象。

现在,我想在前端显示裁剪后的照片。我正在传递患者对象(其中包含记录的所有数据字段,包括裁剪照片)。

我正在考虑将该 blob 对象转换为 base64 并显示它。但问题是我不确定如何在 ejs 模板中使用 croppedPhoto 字段值来转换它。

server.js [查找所有患者并传入 ejs 模板 - 还包括croppedPhoto 字段]

app.get('/', async (req, res) => {
    const patients = await Patient.find();
    res.render('index', { patients: patients });
});

index.ejs [想在img标签中显示照片]

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

谢谢!!

【问题讨论】:

    标签: node.js express blob ejs multer


    【解决方案1】:

    通常,在将文件上传到服务器时,您必须避免将文件本身保存在数据库中,而是可以将文件从客户端的桌面移动到您想要的目录(您的应用程序图像文件夹使用Express file upload 存储图像),然后将该文件的path 保存在数据库中,通常是这样的:/images/test.png

    这是一个例子:

    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" });
    }
    });
    

    然后在你的 EJS 模板中,就很容易访问图片的 src 了:&lt;img src="OBJECT.ImgURL" /&gt;

    【讨论】:

    • 嗨,杰西,谢谢您的回答。我已经知道如何使用 multer 将图像保存在目录中。我只是想尝试一下它保存在数据库中的场景。
    猜你喜欢
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2017-11-20
    • 2019-06-07
    • 1970-01-01
    • 2015-03-29
    相关资源
    最近更新 更多