我正在尝试从 react native 捕获图像并将其上传到服务器,但是当我发出 http 请求时出现以下错误:
[类型错误:网络请求失败]
这是我的代码,我遵循了本教程:
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://', ''),
});
编辑 02-07-2020我终于在这里找到了解决方案:
https://github.com/facebook/react-native/issues/28551#issuecomment-610652110
最佳答案
第一个问题是 imageUri 本身。如果假设照片路径是/user/.../path/to/file.jpg。然后 android 中的文件选择器将 imageUri 值作为 file:/user/.../path/to/file.jpg 而 iOS 中的文件选择器将 imageUri 值作为 file:///user/.../path/to/文件.jpg。
第一个问题的解决方法是在android的formData中使用file://而不是file:。
第二个问题是我们没有使用正确的 mime 类型。它在 iOS 上运行良好,但在 Android 上却不行。更糟糕的是,文件选择器包将文件类型指定为“图像”,但没有提供正确的 mime 类型。
解决方案是在字段类型的 formData 中使用适当的 mime 类型。例如:.jpg 文件的 mime-type 为 image/jpeg,.png 文件的 mime-type 为 image/png。我们不必手动执行此操作。相反,您可以使用非常著名的 npm 包名为 mime .
import mime from "mime";
const newImageUri = "file:///" + imageUri.split("file:/").join("");
const formData = new FormData();
formData.append('image', {
uri : newImageUri,
type: mime.getType(newImageUri),
name: newImageUri.split("/").pop()
});
关于javascript - 响应 native 上传图像的网络请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62450971/