Home > Enterprise >  Cannot make a request of image with expo-camera takePictureAsync method to node.js backend server
Cannot make a request of image with expo-camera takePictureAsync method to node.js backend server

Time:01-13

I am struggling from taking pictures with expo camera on react native and sending the cache image to my node.js backend server and then my backend server appends this to a formdata object and sends it to my webservice. I searched a lot about the operations between my frontend and backend but couldn't find the exact true answer.

My express-node backend server getting images with multer.

I have a react native frontend code like below in order to send my image data I got as returned object of takePictureAsync method of expo-camera:

CLIENT SIDE


//react native client side
 const takePicture = async () => {
   if (cameraRef.current) {
     const options = { quality: 0.5, base64: true, skipProcessing: true };
     const data = await cameraRef.current.takePictureAsync(options);
     const source = data.uri;

     if (source) {
       await cameraRef.current.pausePreview();
       setIsPreview(true);
       uploadFile(source);
       console.log('picture source', source);
     }
   }
 };

Then I get 404 status error from my backend when I try to send this image data like below with axios to my node.js backend server:


//react native client side
    async function uploadFile(photo) {
    const formData = new FormData();

    formData.append('file', {
      uri: photo,
      name: 'test',
      mimetype: 'image/jpeg',
    });

    await axios
      .post('http://MyLocalIpAdress:3000/photo-upload', formData, {
        headers: {
          Accept: 'application/json',
          'Content-Type': 'multipart/form-data',
        },
      })
      .then((res) => {
        console.log(res.data);
        return res.data;
      });
  }

SERVER SIDE

My Node.js backend endpoint is as below:


router.post(
  '/photo-upload',
  multer({ storage: multer.memoryStorage() }).single('file'),
  async (req, res) => {
    if (req.file) {
      try {
        // Transfers uploaded image through webservice
        const form = new FormData();
        form.append('file', req.file.buffer, {
          contentType: req.file.mimetype,
          filename: req.file.originalname,
        });

        res.status(200).send({
          message: 'Success'
        });
      } catch (err) {
        res.status(500).send({
          message: `Could not upload the file: ${req.file.originalname}. ${err}`,
        });
      }
    } else {
      return res.status(400).send({ message: 'Please upload a file!' });
    }
  })

I couldn't figure out whether I'm doing things wrong on server side or client side and the way of doing it.

CodePudding user response:

I faced same issue with sending image data to backend using formData. There are a couple of tricks to solve this:

Solution 1:

const formdata = new FormData();
formdata.append('image[]', {
          name: 'test',
          type: imageurl?.type,
          uri:
            Platform.OS !== 'android'
              ? 'file://'   photo
              : photo,
        });
const res = await axios.post('http://MyLocalIpAdress:3000/photo-upload', formdata, {
        headers: {
          Accept: '*/*',
          'Content-type': 'multipart/form-data',
        },
      });

Solution 2: (My personal choice) is to use a library to upload the data. rn-fetch-blob is something that I have used to solve this. If you plan to use this, go through the documentation and implement it.

   RNFetchBlob.fetch('POST', 'http://MyLocalIpAdress:3000/photo-upload', 
      {
        Authorization : "Bearer access-token",
        'Content-Type' : 'multipart/form-data',
    }, [
    // element with property `filename` will be transformed into `file` in form data
    { name : 'avatar', filename : 'avatar.png', data: binaryDataInBase64},
    // custom content type
    { name : 'avatar-png', filename : 'avatar-png.png', type:'image/png', data: binaryDataInBase64},
    // part file from storage
    { name : 'avatar-foo', filename : 'avatar-foo.png', type:'image/foo', data: RNFetchBlob.wrap(path_to_a_file)},
    // elements without property `filename` will be sent as plain text
    { name : 'name', data : 'user'},
    { name : 'info', data : JSON.stringify({
      mail : '[email protected]',
      tel : '12345678'
    })},
  ]).then((resp) => {
    // ...
  }).catch((err) => {
    // ...
  })
  •  Tags:  
  • Related