gpt4 book ai didi

react-native - 安卓 : Network Request Failed when trying to upload image with fetch

转载 作者:行者123 更新时间:2023-12-03 17:26:11 25 4
gpt4 key购买 nike

我正在尝试将图像从存储上传到一个安静的 API,但我在 Android 上不断收到网络请求失败(这意味着请求甚至没有通过),还没有在 iOS 上检查,因为我不需要那部分然而。 API 已经在工作,并且已经用 Postman 进行了测试。

React Native 代码是:

  body.append('vehicles',{ 
resource_id: 2,
resource: 'vehicles',
cat_file_id: fileId,
active: 1,
vehicles: photo, //<- photo value below
name: 'vehicles',
type: 'image/jpeg'
})

fetch(`${BASE_URL}/files`, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
Accept: "*/*",
Authorization: 'Bearer '+auth
},
body: body

}).then(response => response.json())
.then(response => {
console.log('IMAGE RESPONSE', response)
})
.catch(error => console.log('ERROR', error))

照片值看起来像 file:///storage/emulated/0/DCIM/...
响应:
ERROR TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (fetch.umd.js:473)
at XMLHttpRequest.dispatchEvent (event-target-shim.js:818)
at XMLHttpRequest.setReadyState (XMLHttpRequest.js:574)
at XMLHttpRequest.__didCompleteResponse (XMLHttpRequest.js:388)
at XMLHttpRequest.js:501
at RCTDeviceEventEmitter.emit (EventEmitter.js:189)
at MessageQueue.__callFunction (MessageQueue.js:436)
at MessageQueue.js:111
at MessageQueue.__guard (MessageQueue.js:384)
at MessageQueue.callFunctionReturnFlushedQueue (MessageQueue.js:110)

在 Postman 上,请求看起来像这样:

Headers

Body

已经试过了:
  • 删除接受标题
  • 将接受值更改为“应用程序/json”
  • 删除 file://来自图片网址
  • 已添加 android:usesCleartextTraffic="true"到 list

  • 已查:
  • 没有值为空或未定义的值
  • 有可用的互联网连接,应用程序上的所有其他网络请求都正常工作
  • 验证正确

  • React Native 版本是 0.61.5

    最佳答案

    我发现您的代码中缺少一行 let formData = new FormData(); .但不确定是这里的确切问题。
    顺便说一下,这里是我的一个项目中的示例工作代码,我根据您的上下文对其进行了自定义。

  • 添加您的身份验证
  • 替换 ImageURI带有图像路径和 URL_SAVE_IMAGE端点网址
    const newImage = {
    resource_id: 2,
    resource: 'vehicles',
    cat_file_id: 1,
    active: 1,
    vehicles: ImageURI,
    name: "my_photo.jpg",
    type: "image/jpg",
    };

    let formData = new FormData();
    formData.append("vehicles", newImage);

    return fetch(URL_SAVE_IMAGE, {
    method: 'POST',
    headers: {
    "Content-Type": "multipart/form-data"
    },
    body: formData
    }).then(response => response.json());

  • 它应该工作!

    关于react-native - 安卓 : Network Request Failed when trying to upload image with fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60728339/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com