问题
I am having great trouble in uploading an image via fetch and react-native-image-picker to multer and express js 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.
It is really frustrating
Can anyone please help?
回答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'
来源:https://stackoverflow.com/questions/60752731/multer-react-native-image-picker-image-upload-not-working-on-ios