缓冲数组到字符串然后保存在目录中

问题描述

我是 React 的新手,我目前面临一个问题,我用 Express.js 编写 API,我在其中接收到您从移动设备上传到缓冲区数组中的任何所谓的图像,现在我必须将其转换为字符串并为其添加扩展名(假设为 .jpg)并将其存储到 MongoDB Atlas 这里是我用 Express 编写的 API ```module.exports.submitFormDataFile = async (req,res) => {

var hkeyArray = [];
    const body = req.body;
    const collection_name = body.form_collect_name;

    const formstructureresult = await Formsstructure.findOne({
        collection_name: collection_name
    });

    formstructureresult.formdata.forEach((eachData) => {
        if (eachData.element === 'file') hkeyArray.push(eachData.hkey);
    });

    //  console.log(hkeyArray)

    hkeyArray.forEach((element) => {
        //In this part I was supposed to convert it in string and save with extension 
        console.log(req.files[element].data);
    });

    if (body._id != '' && body._id != null) {
        try {

            const result = db.collection(
                collection_name
            );

            const results = await result.findOne({
                _id: mongoose.Types.ObjectId(body._id)
            });

            if (!results) {
                res.status(200).json({
                    ERROR: 1,MESSAGE: 'Invalid Record'
                });
            } else {
                delete body._id;
                var newvalues = { $set: body};
                const resu = await result.updateOne(results,newvalues);
                if (!resu) {
                    res.status(404).json({
                        ERROR: '1',MESSAGE: 'Unable to update'
                    });
                } else {
                    res.status(200).json({
                        SUCCESS: '1',MESSAGE: 'Record Updated Successfully'
                    });
                }
            }
        } catch (error) {
            console.log(error,'error');
        }
    }
};

由于一切都是动态的,所以我从 集合获取 hkey 这是 MongoDB 中的名称,并基于 req.body 获取其他集合> 接收和 byteArray 也从 req.body 接收并将其转换为字符串我必须更新文档,如代码所示

解决方法

问题解决了!就我而言,解决方案很简单,我只是相应地更改了代码

hkeyArray.forEach((element) => {
        //In this part I was supposed to convert it in string and save with extension 
        var imagedata = req.files[element].data;
        let buff = new Buffer.from(imagedata,'base64');
        fs.writeFile(`element+'.jpg'`,buff,function (err) {
            if (err) throw err;
            console.log('Saved!');
          });
          body[element] = element+'.jpg'
    });