当我更新个人资料图片时,我的数据库获得空值。我已经尝试了很多次,但无法弄清楚我的错误。我想学习如何将图像上传到Cloudinary并将文件名保存到MongoDB。
注意:图像已成功上传到Cloudinary,但是在MongoDB中图像的值为空。
与Cloudinary代码的本地响应
const ChangePhoto = ({navigation, route}, props) => {
const getDetails = type => {
if (route.params) {
switch (type) {
case 'id':
return route.params.id;
case 'name':
return route.params.name;
}
}
return '';
};
const [image, setImage] = useState([]);
const [name, setName] = useState(getDetails('name'));
const [id, setId] = useState(getDetails('id'));
const updateDetails = async () => {
fetch('http://192.168.*.*:5000/avatar_update', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: route.params._id,
name,
image: [image.name],
}),
})
.then(res => res.json())
.then(data => {
Alert.alert(`${data.name} is updated successfuly`);
navigation.navigate('Home');
})
.catch(err => {
Alert.alert('someting went wrong');
});
};
function selectImage() {
let options = {
title: 'You can choose one image',
maxWidth: 256,
maxHeight: 256,
noData: true,
mediaType: 'photo', // other values 'video', 'mixed'
storageOptions: {
skipBackup: true,
path: 'images',
},
};
ImagePicker.showImagePicker(options, response => {
if (response.didCancel) {
console.log('User cancelled photo picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = {
uri: response.uri,
type: response.type,
name:
response.filename ||
response.uri.substr(response.uri.lastIndexOf('/') + 1),
};
console.log({source});
// ADD THIS
cloudinaryUpload(source);
// });
}
});
}
const cloudinaryUpload = image => {
const data = new FormData();
data.append('file', image);
data.append('upload_preset', 'NepAus');
data.append('cloud_name', 'dpwxgbsjg');
fetch('https://api.cloudinary.com/v1_1/dpwxgbsjg/image/upload', {
method: 'post',
body: data,
})
.then(res => res.json())
.then(data => {
setImage(data.url);
})
.catch(err => {
Alert.alert('An Error Occured While Uploading');
});
};
服务器端代码:
router.post("/avatar_update", requireToken, async (req, res) => {
User.findByIdAndUpdate(req.user.id, {
image: req.user.image,
})
.then((data) => {
console.log(data);
res.send(data);
})
.catch((err) => {
console.log(err);
});
});