0

I want to send multiple images along with some other fields but I want to send those in JSON format instead of formData.

On the server I am using multer for image storing.

Refer to the link for the React code. https://codesandbox.io/s/react-hooks-usestate-1h8cw?file=/src/index.js:1017-1023

The images are uploading and displaying but I am not able to find a way to send it on server side in JSON format.

Server-side code

const router = require("express").Router();
const City = require('../../model/city');
const multer = require('multer')
var upload = multer({
    dest: 'uploads/'
})

//Post City at this route 
router.post('/create', upload.array('Images', 12), async (req, res) => {
    console.log(req.files);
    const city = new City({
        City: req.body.City,
        Description: req.body.Description,
        Images: req.files.path
    });
    try {
        let check;
        check = await City.findOne({
            City: req.body.City
        });
        // res.send(check);
        if (check) {
            res.send({
                "message": "City already exists"
            })
        } else {
            const savedCity = await city.save();
            res.send(savedCity);
        }
    } catch (err) {
        res.status(400).send(err);
    }


});
Ryuk
  • 362
  • 1
  • 6
  • 21
  • you can't send it in json. – demkovych Jun 25 '20 at 12:51
  • 1
    the only way is to convert every image to base64 and send them as a string but your BE will fail sometimes because base64 string will be super long. – demkovych Jun 25 '20 at 12:52
  • I am getting the string as blob:http://localhost:3001/2f6ba111-1f03-4266-b7ee-0c436452c782 when I upload the images. Is there anyway I can send this as string and save it in db and retrieve back as image – Ryuk Jun 25 '20 at 17:54

0 Answers0