使用 mongoose 通过 React 应用程序将图像上传到 mongodb 数据库

2024-05-19

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

我尝试使用 axios 通过 post 请求将图像发送到猫鼬服务器,但它不起作用。

这就是我如何将图像存储在带有预览的 React 组件中:

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

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

我能做些什么 ?


你需要multer https://www.npmjs.com/package/multer在您的服务器上处理多部分/表单数据。您可以以两种方式将图像存储到数据库中的某个字符串存储中,并在需要时解码该字符串。或者您可以将图像存储在服务器上并将该图像的 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})
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 mongoose 通过 React 应用程序将图像上传到 mongodb 数据库 的相关文章

随机推荐