我试图捕获图像,并将图像从react native上载到服务器,但是在发出http请求时出现以下错误:
[TypeError:网络请求失败]
这是我的代码,我已经按照本教程进行操作:
https://heartbeat.fritz.ai/how-to-upload-images-in-a-react-native-app-4cca03ded855
import React from 'react';
import {View, Image, Button} from 'react-native';
import ImagePicker from 'react-native-image-picker';
export default class App extends React.Component {
state = {
photo: null,
};
createFormData = (photo) => {
const data = new FormData();
data.append('photo', {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === 'android'
? photo.uri
: photo.uri.replace('file://', ''),
});
data.append('id', 1);
return data;
};
handleChoosePhoto = () => {
const options = {
noData: true,
};
ImagePicker.launchImageLibrary(options, (response) => {
if (response.uri) {
this.setState({photo: response});
}
});
};
handleUploadPhoto = () => {
fetch('http://192.168.1.104:3000/', {
method: 'POST',
body: this.createFormData(this.state.photo),
})
.then((response) => response.text())
.then((response) => {
console.log('upload success', response);
})
.catch((error) => {
console.log('upload error', error);
});
};
render() {
const {photo} = this.state;
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
{photo && (
<React.Fragment>
<Image
source={{uri: photo.uri}}
style={{width: 300, height: 300}}
/>
<Button title="Upload" onPress={this.handleUploadPhoto} />
</React.Fragment>
)}
<Button title="Choose Photo" onPress={this.handleChoosePhoto} />
</View>
);
}
}
我尝试过:
我注意到只有在将照片对象添加到“ FormData”时,该请求才会失败,也就是说,当我删除以下代码时,http请求将正确运行:
data.append('photo', {
name: photo.fileName,
type: photo.type,
uri:
Platform.OS === 'android'
? photo.uri
: photo.uri.replace('file://', ''),
});
我终于在这里找到了解决方案:
https://github.com/facebook/react-native/issues/28551#issuecomment-610652110
答案 0 :(得分:0)
几天前有类似的问题。 对我来说,问题是 photo.type 返回错误的类型。所以我只是手动添加。
fd.append('documentImages', {
name: getImgId(img.uri) + '.jpg',
type: 'image/jpeg',
uri: Constants.platform.android
? img.uri
: img.uri.replace('file://', ''),
})
答案 1 :(得分:0)
This solution也可以:
在我的项目中,本机版本为react-native 0.62。 我将脚蹼更新为“ 0.41.0”,它可以正常工作。
在gradle.properities
FLIPPER_VERSION = 0.41.0
gradle.properties
位于PROJECT_ROOT/android
答案 2 :(得分:-1)
const URL = "ANY_SERVER/upload/image"
const xhr = new XMLHttpRequest();
xhr.open('POST', url); // the address really doesnt matter the error occures before the network request is even made.
const data = new FormData();
data.append('image', { uri: image.path, name: 'image.jpg', type: 'image/jpeg' });
xhr.send(data);
xhr.onreadystatechange = e => {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
console.log('success', xhr.responseText);
} else {
console.log('error', xhr.responseText);
}
};