我在做与反应原生的应用程序。现在我试图从手机发送图像到服务器(Node Js)。为此,我使用react-native-image-picker。问题是,当我发送图像时它保存一个文件,但它是空的不包含照片。我认为这个问题可能是因为在不同的设备,服务器无法访问到图像的路径。但我不知道我该怎么做。将文件发送到节点JS服务器
阵营母语:
openImagePicker(){
const options = {
title: 'Select Avatar',
storageOptions: {
skipBackup: true,
path: 'images'
}
}
ImagePicker.showImagePicker(options, (imagen) =>{
if (imagen.didCancel) {
console.log('User cancelled image picker');
}
else if (imagen.error) {
console.log('ImagePicker Error: ', imagen.error);
}
else if (imagen.customButton) {
console.log('User tapped custom button: ', imagen.customButton);
}
else {
let formdata = new FormData();
formdata.append("file[name]", imagen.fileName);
formdata.append("file[path]", imagen.path);
formdata.append("file[type]", imagen.type);
fetch('http://X/user/photo/58e137dd5d45090d0b000006', {
method: 'PUT',
headers: {
'Content-Type': 'multipart/form-data'
},
body: formdata
})
.then(response => {
console.log("ok");
})
.catch(function(err) {
console.log(err);
})
}})}
节点JS:
addPhotoUser = function (req, res) {
User.findById(req.params.id, function(err, user) {
fs.readFile(req.body.file.path, function (err, data) {
var pwd = 'home/ubuntu/.../';
var newPath = pwd + req.body.file.name;
fs.writeFile(newPath, data, function (err) {
imageUrl: URL + req.body.file.name;
user.save(function(err) {
if(!err) {
console.log('Updated');
} else {
console.log('ERROR: ' + err);
}
res.send(user);
});
});
});
});
};
谢谢!我试着第一个解决方案。我在后台发送它很好,但在尝试访问映像时没有正确保存并且没有显示任何内容。 –
真的发生了什么? – Codesingh
看到我上面的答案。手机中的uri无法远程访问。当他试图读取它时,他正试图读取uri在手机上的图像。 – klvs