【发布时间】:2026-01-23 06:50:02
【问题描述】:
我已经在堆栈溢出、Github 问题、要点等方面查看了所有可能的解决方案。他们都没有工作。
基本上,我正在尝试将通过 react-native-camera 捕获的图像上传到 Java API,它可以在 iOS 上的模拟器和物理设备上运行。
function handleOnPictureTaken (image) {
const imageName = image.uri.split('/').pop()
const imageExtension = imageName.split('.').pop()
const imageType = `image/${imageExtension}`
const source = { uri: image.uri, type: imageType, name: imageName }
onPhotoSelected(source)
}
function onPhotoSelected (image) {
const photoData = new FormData()
image = {
...image,
uri: image.uri.replace('file://', '')
}
photoData.append('file', image)
uploadFile(photoData)
}
function uploadFile(image) {
const config = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
credentials: 'include'
}
if (method === 'POST' || method === 'PUT') {
if (config.headers['Content-Type'] === 'application/json') {
config.body = JSON.stringify(data)
} else {
config.body = data
}
}
return fetch(url, config).then(checkJSON)
.then(res => res.text())
.then(parseJSON)
.catch(rejectRequest)
}
这在 iOS 上完美运行。但在 Android 上,我不断收到Network request failed,如下所示
Stack trace: TypeError: Network request failed
at anonymous (http://192.168.0.103:8081/index.bundle?platform=android&dev=true&minify=false:28469:31)
at call (native)
at dispatchEvent (http://192.168.0.103:8081/index.bundle?platform=android&dev=true&minify=false:34597:31)
at setReadyState (http://192.168.0.103:8081/index.bundle?platform=android&dev=true&minify=false:33681:33)
at __didCompleteResponse (http://192.168.0.103:8081/index.bundle?platform=android&dev=true&minify=false:33508:29)
at apply (native)
at anonymous (http://192.168.0.103:8081/index.bundle?platform=android&dev=true&minify=false:33618:52)
at apply (native)
at emit (http://192.168.0.103:8081/index.bundle?platform=android&dev=true&minify=false:6202:42)
at apply (native)
at __callFunction (http://192.168.0.103:8081/index.bundle?platform=android&dev=true&minify=false:5626:49)
at anonymous (http://192.168.0.103:8081/index.bundle?platform=android&dev=true&minify=false:5348:31)
at __guard (http://192.168.0.103:8081/index.bundle?platform=android&dev=true&minify=false:5580:15)
at callFunctionReturnFlushedQueue (http://192.168.0.103:8081/index.bundle?platform=android&dev=true&minify=false:5347:21)
我一直在努力完成这项工作。物理 Android 设备在同一个 WiFi 上。正常的 POST 请求正在工作。但只有上传文件失败。
如果有人有任何建议,请告诉我。
【问题讨论】:
-
您的 AndroidManifest.xml 中是否允许 http 流量?
-
检查 android:usesCleartextTraffic="true" 是否出现在您的清单中
-
我刚刚添加了那行。在我的设备上重新运行
npm run android。但仍然没有帮助。 -
但 usesCleartextTraffic 用于允许
http请求,默认情况下允许https请求。我正在使用https拨打电话。 -
你能在Android Studio中查看logcat吗?
标签: android react-native fetch