I am trying to upload image file with react native, by using nodejs multipart api, but the file is not getting sent from the FE. If I console req.files its undefined at server side. Here is my react native code:
var options = {
title: 'Select Image',
storageOptions: {
skipBackup: true,
path: 'images'
}
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
console.log('User selected a file form camera or gallery', response);
const data = new FormData();
data.append('name', 'avatar');
data.append('file', {
uri: response.uri,
type: response.type,
name: response.fileName
});
const config = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: data,
};
fetch("http://myapi.com/api/v1/user", config)
.then((checkStatusAndGetJSONResponse) => {
console.log(checkStatusAndGetJSONResponse);
}).catch((err) => { console.log(err) });
}
}
)
and Nodejs code:
const storage = multer.memoryStorage({
destination:(req, file, callback) => {
callback(null, '')
}
});
const upload = multer({ storage: storage }).array('file');
upload(req,res,(err) => {
if(err) {
console.log('ERROR: ',err);
return res.end("Error uploading file.");
}else{
console.log('REQUEST: ',req.files);
}
});
I am not able to upload image with some user data, please let me know what am doing wrong here Thanks