【问题标题】:Upload image through a react app to a mongodb data base with mongoose使用 mongoose 通过 React 应用程序将图像上传到 mongodb 数据库
【发布时间】:2019-05-31 08:47:19
【问题描述】:

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

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

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

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

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

我能做什么?

【问题讨论】:

    标签: reactjs image mongoose


    【解决方案1】:

    您需要在您的服务器上使用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})
        }
    

    【讨论】:

    • 坦克很多!我终于成功了!我这样做的方法是使用 FileReader() 将图像转换为字符串,然后将其作为字符串存储到数据库中。为此,我现在存储 imagePreviewUrl 而不是输入表单直接给出的文件。
    猜你喜欢
    • 2020-06-28
    • 2016-06-03
    • 2012-02-29
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 2017-06-09
    • 2020-10-19
    • 1970-01-01
    相关资源
    最近更新 更多