我正在尝试捕获图像并将其从 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>
);
}
}
我试过:
- 将"内容:多部分/表单数据"添加到 http 请求标头 将接受:
- 接受:应用程序/json"添加到 http 请求标头
我注意到请求失败,只有当我将照片对象添加到"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/file.jpg 给出
。第一个问题的解决方案是使用 file://而不是 file:在 android 的 formData 中。
第二个问题是我们没有使用正确的哑剧类型。它在iOS上运行良好,但在Android上无法正常工作。更糟糕的是,文件选择器包将文件类型作为"图像"给出,并且没有给出正确的 mime 类型。
解决方案是在字段类型的 formData 中使用正确的 mime 类型。例如:.jpg文件的 mime 类型将是图像/jpeg,.png文件将是图像/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 的项目中遇到了同样的问题。 我将鳍状肢更新为"0.41.0",它起作用了。
In gradle.properities
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% 工作