首页 > 解决方案 > 发送带有 Post Form et 的图像,在 based64 中使用节点 Js 进行编码

问题描述

我尝试从帖子表单(我网站上的用户)中获取图像并将其编码为 base64 以记录在我的数据库中,我尝试但是当我获取文件时,只取名称..(“5165151.jpg”)什么我的代码错了吗?

app.post("/postCreas",(req,res)=>{
    const imgUp = new imgModel({

    })
    let title = req.body.title
    let commentaire = req.body.sujet
    let img = req.body.upload
    let postCollection = db.collection('POSTCreas')
   /* let im64= Buffer.from(img, 'binary').toString('base64')   */ 
    console.log("test :"+img) 
        
    
    
    
    postCollection.insertOne({_id:title,title:title, commentaire : [commentaire],fichiers:img})        
    res.redirect("vosCreas")                       
    res.end()    
})

我的表单代码是:

  app.post("/postAstuces",(req,res)=>{
    let title = req.fields.title
    let commentaire = req.fields.sujet
    let img = req.files.upload.toString('base64')
    let postCollection = db.collection('POSTastuces')
    console.log("test : "+img)
    
    
    postCollection.insertOne({_id:title,title:title, commentaire : [commentaire],fichiers:img})        
    res.redirect("vosAstuces")                       
    res.end()    
})

祝你有美好的一天 !

标签: javascriptnode.jsmongodbformspost

解决方案


正如怀疑的那样,您的标签中缺少enctype="multipart/form-data"文件<form>上传所必需的标签。

您还需要确保您的服务器知道如何解析多部分表单数据。如何做到这一点取决于您配置事物的方式。


推荐阅读