Upload image with mongoDB/express/expo/multer in react native

Hi, I tried to upoad an image into mongoDB using express and axios in reactnative (expo). but I can’t figured out how to do this…

I have this in my client :

import * as ImagePicker from 'expo-image-picker';
const [selectedImage, setSelectedImage] = useState('');

const openImagePickerAsync = async () => {
    let permissionResult = await ImagePicker.requestCameraRollPermissionsAsync();

    if (permissionResult.granted === false) {
      alert("Permission to access camera roll is required!");
      return;
    }
    let result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        allowsEditing: true,
        aspect: [4, 3],
        quality: 1,
      });

      if (!result.cancelled) {
        setSelectedImage(result.uri);
      }
  }

const sendFormulaireHandler = () => {
data.append('uploadbar', {
      uri : selectedImage,
      type : 'image',
      name : 'test'
    })
dispatch(BarsActions.createBarManager(data)).then(() =>{
      {errormsg ? Alert.alert("Baraka",errormsg) : null }
      })
};

My createBarManager function :

export const createBarManager = (data) => {
    return async dispatch => {
        try {
            const response = await Api.post('/bar/create-bar',data);
            dispatch({ type: CREATE_BAR_MANAGER,
              payload: response.data,
            });
        } catch (error) {
            dispatch({ type: TOGGLE_ERROR_BARS, payload: "Error" });
        }
    };
};

And my API function :

const multer = require("multer");
const upload = multer({
  limits: {
    //Max of file 5Mo= 5000000 bytes.
    fileSize: 5000000,
  },
  fileFilter(req, file, cb) {
    if (!file.originalname.match(/\.(png|jpg|jpeg)$/)) {
      return cb(
        new Error(
          "too large"
        )
      );
    }
    cb(undefined, true);
  },
});

router.post(
  config.rootAPI + "/bar/create-bar",
  upload.single("uploadbar"),
  async (req, res) => {
    try {
      const userimage = req.file.buffer;
      const imageCrop = await sharp(userimage)
        .resize(820, 360, { fit: sharp.fit.inside, withoutEnlargement: true })
        .png()
        .toBuffer();

      const image = ArrayToString(imageCrop);

      async function () {
          const bar = new BarTMP({
            image,
          });
          await bar.save();
          res.status(201).send({ success: "OK" });
        })
        .catch(function (err) {
          res.status(422).send({
            erreur: "Error.",
          });
        });
    } catch (err) {
      res.status(422).send({
        error:
          "Error",
      });
    }
  },
  (error, req, res, next) => {
    res
      .status(422)
      .send({ error: "Error" });
  }
);

It’s work perfetly with Postman, but i can’t manage with react native…

If someone has an idea…

Thanks

I found a solution, thanks :smiley:

Happy to hear you got things figured out @alphakush. If you have time, I’m sure others in the community and us at Expo would greatly appreciated if you could share your solution so that if others encounter a similar issue they may be able to use your knowledge to help them with their own projects.

Cheers,
Adam

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.