Soudini
Soudini

Reputation: 65

Upload image through a react app to a mongodb data base with mongoose

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 ?

Upvotes: 2

Views: 7177

Answers (1)

Rajan Lagah
Rajan Lagah

Reputation: 2528

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

Upvotes: 1

Related Questions