我在Web服务器上有PHP页面,可以从React Native上传图像。
使用Postman方法POST,form-data key:avatar value: image_file
,一切正常。
我在React Native中尝试过:
let uploadData = new FormData();
uploadData.append('avatar', uploadUri);
fetch(base_url, { method: 'post,', body: uploadData }).then(
(res) => {
var myresponse = res;
console.log(JSON.stringify(myresponse));
//console.log(res);
}
);
我收到服务器错误消息:
{“ type”:“默认”,“ status”:400,“ ok”:false,“ headers”:{“ map”:{“ server”:“ Apache”,“ connection”:“ Upgrade, close“,” content-type“:” text / html“,” vary“:” Accept-Encoding,User-Agent“,” date“:” Wed, 2020年5月20日15:29:15 GMT”,“接受范围”:“字节”,“升级”:“ h2,h2c”}},“ url”:“ http://www./uploadImage.php”,“ _ bodyInit”:{“ _ data”:{“大小” :10154,“ offset”:0,“ blobId”:“ D8041FEE-0479-4CD5-8438-4EFD737561DE”,“ type”:“ text / html”,“ name”:“ uploadImage.php”,“ __ collector”:{ }}},“ _ bodyBlob”:{“ _ data”:{“ size”:10154,“ offset”:0,“ blobId”:“ D8041FEE-0479-4CD5-8438-4EFD737561DE”,“ type”:“ text / html “,” name“:” uploadImage.php“,” __ collector“:{}}}}
比起尝试使用axios:
let uploadData = new FormData();
uploadData.append('avatar', uploadUri);
axios.post(base_url, uploadData).then((res) => {
console.log(res);
});
我从服务器收到以下响应:
“错误”:是,
“ message”:“没有发送文件!”,
“ status”:“错误”,
在PHP上的if($_FILES['avatar'])
上失败。
我不知道该怎么做,在邮递员中,一切都按预期工作。
有人知道该怎么做吗?
我再次测试了它,肯定是我发送的URI出现了问题。
即。如果我查看邮递员,我正在发送的请求:
avatar=@/Users/......image.jpg
,并且在React Native中,我正在发送:
"avatar","file:///Users/.....image.jpg
顺便说一句,我正在使用expo-image-picker选择图像。
答案 0 :(得分:0)
看起来好像已经完成了工作。
let body = new FormData();
//Appending file to body
body.append('avatar', {
uri: uploadUri,
type: 'image/jpeg', //This is the file type .. you can define according to your requirement
name: 'avatar.jpg', //File name you want to pass
});
//Service call
fetch(base_url, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded',
}),
body: body,
})
.then((res) => res.json())
.then((responseJson) => {
//GET RESPONSE SUCCESS OF FAILURE
console.log(JSON.stringify(responseJson));
})
.catch((error) => {
//ERROR
console.log(JSON.stringify(error));
});