使用react native和PHP(CodeIgniter)作为后端的图像上载问题
我有一个以react native和CodeIgniter为后端的应用程序场景 我有一个代码片段可以上传react native image picker拾取的图像,如下所示:使用react native和PHP(CodeIgniter)作为后端的图像上载问题,php,react-native,file-upload,codeigniter-4,react-native-image-picker,Php,React Native,File Upload,Codeigniter 4,React Native Image Picker,我有一个以react native和CodeIgniter为后端的应用程序场景 我有一个代码片段可以上传react native image picker拾取的图像,如下所示: let formData = new FormData(); let imageBody = { uri: newImage, name: 'profilepicture.jpg', type: 'image/jpeg
let formData = new FormData();
let imageBody = {
uri: newImage,
name: 'profilepicture.jpg',
type: 'image/jpeg',
};
formData.append('file', (imageBody)) // case 1 gives network error
formData.append('file', JSON.stringify(imageBody)) //case 2 goes OK
apiUpdateUser(formData)
.then(res => {
this.setState({ showSnack: true, snackText: 'Profile Picture Updated'})
})
.catch(err => {
this.setState({ showSnack: true, snackText: 'Update Failed' })
});
apiUpdateUser
方法如下所示:
export const apiUpdateUser = body => {
return new Promise((resolve, reject) => {
axios
.post(ApiRoutes.updateUser, body, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(res => {
resolve(res.data);
})
.catch(err => {
reject(Constant.network.networkError);
});
});
};
后端处理此上载的Php代码通常为:
$file=$this->request->getFile('file');//in CI
$file=$_FILES['file'];//in normal php
我的问题是,我在$file
变量中没有得到任何东西。无论使用哪种方法,file变量在这两种情况下都是空的
我已经在react native中检查了实现,与在线教程/演示相比,它似乎一点问题也没有。另外,后端的处理方式是显而易见的
我能够实现这个上传邮递员容易,但与反应原生我面临着这个错误。有人能给我点提示吗?我正在使用VUE并使用Axios发送文件。所以我想这可能对你有所帮助 我使用下面的表单数据方式来设置文件或图像
formData.append('file', this.form.image_url, this.form.image_url.name);
这里,this.form.image_url直接引用$event.target.files[0]代码>其中$event以输入为目标
在后端,它与这里的相同
这对我来说很好。我不确定您作为imageBody传递的内容,因此很难对此发表评论。我使用VUE并使用Axios发送文件。所以我想这可能对你有所帮助
我使用下面的表单数据方式来设置文件或图像
formData.append('file', this.form.image_url, this.form.image_url.name);
这里,this.form.image_url直接引用$event.target.files[0]代码>其中$event以输入为目标
在后端,它与这里的相同
这对我来说很好。我不确定您作为imageBody传递的是什么,因此很难对此发表评论。您可以试试这个
let imageBody = {
uri: newImage,
name: 'profilepicture.jpg',
type: 'image/jpeg',
};
apiUpdateUser(imageBody)
.then(res => {
this.setState({ showSnack: true, snackText: 'Profile Picture Updated'})
})
.catch(err => {
this.setState({ showSnack: true, snackText: 'Update Failed' })
});
你可以试试这个
let imageBody = {
uri: newImage,
name: 'profilepicture.jpg',
type: 'image/jpeg',
};
apiUpdateUser(imageBody)
.then(res => {
this.setState({ showSnack: true, snackText: 'Profile Picture Updated'})
})
.catch(err => {
this.setState({ showSnack: true, snackText: 'Update Failed' })
});
事实证明,JSON.stringify()
是罪魁祸首
如果没有这条线,应用程序就会发出网络错误。
这就是为什么我随机添加它只是为了看看这是否是错误的原因
因为,网络错误的问题已经解决了,我没有再考虑它,只是认为这是一个文件上传的问题。事实上,我现在看到这是我一直在使用的react本机flipper版本的一个已知问题,我设法解决了这个问题。结果是JSON.stringify()
是罪魁祸首
如果没有这条线,应用程序就会发出网络错误。
这就是为什么我随机添加它只是为了看看这是否是错误的原因
因为,网络错误的问题已经解决了,我没有再考虑它,只是认为这是一个文件上传的问题。事实上,我现在发现这是我一直在使用的react本机flipper版本的一个已知问题,我成功地解决了这个问题。这导致了同样的命运:(这导致了同样的命运:(