首页 > 解决方案 > 使用 mongoose 通过 React 应用程序将图像上传到 mongodb 数据库

问题描述

我正在为找到的对象创建一个反应应用程序,我希望允许用户上传这些对象的照片

我试图通过带有 axios 的发布请求将图像发送到猫鼬服务器,但它不起作用。

所以这就是我将图像存储在带有预览的反应组件中的方式:

handleImage(event) {
  let reader = new FileReader();
  let file = event.target.files[0];
  reader.onloadend = () => {
    this.setState({
      image: file,
      imagePreviewUrl: reader.result
    });
  }

这就是我发送它的方式:

reader.readAsDataURL(file)

axios.post("/api/putData", {
  id: idToBeAdded,
  author : "TODO", //TODO
  title: infos.title,
  type: infos.type,
  reward: this.state.reward,
  description: infos.description,
  image: infos.image,
});

这是我处理另一端请求的代码:

router.post("/putData", (req, res) => {
  let data = new Data();

  const { id, author, title, type, reward, description, image } = req.body;

  /*if ((!id && id !== 0) || !message) {
    return res.json({
      success: false,
      error: "INVALID INPUTS"
    });
  }*/
  data.title = title;
  data.type = type;
  data.reward = reward;
  data.description = description;
  data.author = author;
  data.id = id;
  data.image.data = image;
  data.image.contentType = 'image/png'
  data.save(err => {
    if (err) return res.json({ success: false, error: err });
    return res.json({ success: true });
  });
});

因此,此图像是表单的一部分,当我在没有图像的情况下提交它时,我在数据库中有一个没有任何图像的新文档(这没关系),但是当我尝试加载一个时,没有创建任何文档。

我能做些什么 ?

标签: reactjsimagemongoose

解决方案


您需要在服务器上使用multer来处理 multipart/form-data。您可以将图像以两种方式存储到数据库中的某个字符串存储中,并在需要时解码该字符串。或者您可以将图像存储在服务器上并将其 URL 存储在您的数据库中。因此,当您需要使用图像时,您可以使用 URL。
要在服务器上上传图像,您可以

import multer from 'multer'

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
            var dirName =path.join(process.cwd(), './files/')
            console.log(dirName)
            if (!fs.existsSync(dirName)){
                    fs.mkdirSync(dirName);
            }
                cb(null,dirName)
        }
  },
  filename: function (req, file, cb) {
        cb(null, Date.now()+'-'+file.originalname)
  }


  })
var upload = multer({ storage: storage })

router.post("/putData",upload.single('files'), (req, res) => {
  console.log(reqs.file.destination) // image url
  console.log(JSON.parse(req.body)) // other things
})

在前端添加

handleSubmit(e){
        var fd = new FormData()
        fd.append('files',this.state.files[i][0],this.state.files[i][0].name)
        var statebody = Object.assign({},this.state,{files:null})
        fd.append('state',JSON.stringify(statebody))
        axios.post('/api/',fd)
                    .then((res)=>{
            console.log(res)
        }).catch((e)=>{
            console.log(e)
        })
    }

    handleFiles(e){
        this.setState({files:e.target.files})
    }

推荐阅读