我正在尝试捕获图像并将其从 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://', ''),
});
我终于在这里找到了解决方案:
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:。
第二个问题是我们没有使用正确的哑剧类型。它在 iOS 上运行良好,但在 Android 上则不行。更糟糕的是,文件选择器包将文件类型指定为“图像”,并且没有提供正确的 mime 类型。
解决方案是在字段类型的 formData 中使用正确的 mime-type。例如:.jpg 文件的 mime 类型为 image/jpeg,.png 文件的 mime 类型为 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()
});
这个解决方案也有效:
我在使用react-native版本0.62的项目中也遇到了同样的问题。 我将 Flipper 更新为“0.41.0”并且它起作用了。
在 gradle.properties 中
FLIPPER_VERSION=0.41.0
gradle.properties
位于PROJECT_ROOT/android
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);
}
};
前几天也遇到过类似的问题。 对我来说,问题是 photo.type 返回错误的类型。所以我只是手动添加它。
fd.append('documentImages', {
name: getImgId(img.uri) + '.jpg',
type: 'image/jpeg',
uri: Constants.platform.android
? img.uri
: img.uri.replace('file://', ''),
})
const launchCamera = () => {
let options = {
storageOptions: {
skipBackup: true,
path: "images",
},
};
ImagePicker.launchCamera(options, (response) => {
console.log("Response = ", response);
if (response.didCancel) {
console.log("User cancelled image picker");
} else if (response.error) {
console.log("ImagePicker Error: ", response.error);
} else if (response.customButton) {
console.log("User tapped custom button: ", response.customButton);
alert(response.customButton);
} else {
const source = { uri: response.uri };
console.log(
"response in image pleae chec nd xcjn",
JSON.stringify(response)
);
this.setState({
filePath: response,
fileData: response.data,
fileUri: response.uri,
});
}
imageUpload(response);
});
};
const imageUpload = (imageUri) => {
console.log('imageuril',imageUri);
const newImageUri = "file:///" + imageUri.assets[0].uri.split("file:/").join("");
const imageData = new FormData()
imageData.append("file", {
uri: newImageUri,
type: mime.getType(newImageUri),
name: newImageUri.split("/").pop()
})
console.log("form data", imageData)
axios({
method: 'post',
url: 'https://example.com/admin/api/v1/upload_reminder/1',
data: imageData
})
.then(function (response) {
console.log("image upload successfully", response.data)
}).then((error) => {
console.log("error riased", error)
})
}
使用此代码 100% 有效
经过近两天的努力,我得到了解决方案。某些移动设备不会在图像 uri 之前添加 file://,这会导致问题。所以你必须在图像 uri 之前对其进行硬编码。
formData1.append('photo', {
uri: "file://"+formData.photo,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});