【问题标题】:buffer Array to String and then saving in directory缓冲区数组到字符串,然后保存在目录中
【发布时间】:2021-04-28 07:07:41
【问题描述】:

我是 React 的新手,我目前面临一个问题,即我在 Express.js 中编写了 API,在该 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');
        }
    }
};

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

【问题讨论】:

    标签: node.js express file-upload buffer bufferedimage


    【解决方案1】:

    问题解决了!在我的情况下,解决方案很简单,我只是相应地更改了代码

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-14
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多