2

I am having trouble in uploading an image via fetch and react-native-image-picker to Multer and Express backend.

Below is my React Native code:

try {

 const data = new FormData();

  data.append('image', {
    name: photo.fileName,
    type: photo.type,
    uri:
      Platform.OS === 'android' ? photo.uri : photo.uri.replace('file://', ''),
  });

 data.append('id', id)

    fetch(`${API}save-image`, {
      method: 'POST',
     
      body: data,
    })
      .then(response => response.json())
      .then(response => {
        console.log('upload succes', response);
      })
      .catch(error => {
        console.log('upload error', error);
      });
  } catch (error) {
    console.log(error);
    if (error.response !== undefined) {
      message = error.response.data.message;
    } else {
      message = error;
    }

    return Promise.reject(message);
  }

image variable is the response object we get from a react-native-image-picker library that contains image data and uri with other needed items.

In the backend I am trying to log in the req.files object that is configured by Multer:

const Storage = multer.diskStorage({
    destination(req, file, callback) {
        callback(null, path.join(__dirname, '../uploads/'));
    },
    filename(req, file, callback) {
        callback(null, new Date().toISOString() + '_' + file.originalname);
    },
});

const upload = multer({
    storage: Storage,
    limits: { fieldSize: 25 * 1024 * 1024 },
});
router.post(
    '/save-image',
    upload.array('image', 3),
    controller.saveImage
);

In the controller I will just console.log(req.files) and then return success message.

I am able to see the console log in case of Android emulator but not on iOS emulator.

In fact the image it seems is not being send to the backend. But there is no error on the backend side and it is not logged in case of iOS.

1 Answer 1

1

There was an issue with react-native and flipper version below 0.39 that caused network requests with file upload to fail, try to manually update your flipper version. In your podfile:

versions['Flipper'] ||= '~> 0.51.0'
1
  • 1
    thanks i was stuck on this for many days and got it fixed after updating flipper version
    – Jose Kj
    Commented Aug 11, 2020 at 15:39

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.