通过React应用程序将图像上传到带猫鼬的mongodb数据库 [英] Upload image through a react app to a mongodb data base with mongoose

查看:63
本文介绍了通过React应用程序将图像上传到带猫鼬的mongodb数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这就是我将图像存储在带有预览的react组件中的方法:

  handleImage(event){让reader = new FileReader();让文件= event.target.files [0];reader.onloadend =()=>{this.setState({图像文件,imagePreviewUrl:reader.result});} 

这就是我发送的方式:

  reader.readAsDataURL(文件)axios.post("/api/putData",{id:idToBeAdded,author:"TODO",//TODO标题:infos.title,类型:infos.type,奖励:this.state.reward,说明:infos.description,图片:infos.image,}); 

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

  router.post("/putData",(req,res)=> {let data = new Data();const {id,作者,标题,类型,奖励,描述,图像} = req.body;/* if((!id&&id!== 0)||!message){返回res.json({成功:错误,错误:输入无效"});} */data.title =标题;data.type =类型;data.reward =奖励;data.description =说明;data.author =作者;data.id = id;data.image.data =图片;data.image.contentType ='图像/png'data.save(err => {if(err)返回res.json({成功:false,错误:err});返回res.json({success:true});});}); 

因此,此图像是表单的一部分,当我不带图像提交它时,数据库中就有一个没有任何图像的新文档(可以),但是当我尝试加载一个图像时,就不会创建文档.>

我该怎么办?

解决方案

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

 从"multer"导入multervar storage = multer.diskStorage({目的地:功能(要求,文件,cb){var dirName = path.join(process.cwd(),'./files/')console.log(dirName)如果(!fs.existsSync(dirName)){fs.mkdirSync(dirName);}cb(null,dirName)}},文件名:函数(要求,文件,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)//图片网址console.log(JSON.parse(req.body))//其他}) 

在前端添加

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

I'm creating a react app for found objects and I want to allow users to upload photos of these objects

I tried to send the image through a post request with axios to a mongoose server but it doesn't work.

So this is how I store the image in the react component with a preview :

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

and this is how I send it :

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

Here is my code to handle the request on the other side :

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

So this image is part of a form and when I submit it without the image I have a new document in the DB without any image (which is okay) but when I try to load one no document is created.

What can I do ?

解决方案

You need multer at your server to process multipart/form-data. You can store images in 2 way concert them into some string store that in DB and when required decode that string. Or you can store image on server and store URL of that in your DB. So when you required to use image you can use URL for that.
To upload image on server you can

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

on Front end add

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

这篇关于通过React应用程序将图像上传到带猫鼬的mongodb数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆