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.