在react native中通过PUT方法上载文件

Uploading file via PUT method in react-native

本文关键字:PUT 方法 上载 文件 react native      更新时间:2023-12-14

我正试图将文件(图像)从我的react原生应用程序上传到后端服务器。RESTFUL后端服务器接受通过特定url上的PUT方法发送的文件。我被困在react native上,试图找到通过PUT方法发送文件的正确方法
我正在尝试复制
的行为curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"

我在浏览器上找到了这样做的XMLHttpRequest方法,但在react native上不起作用。有人经历过这一切吗?请帮帮我!!!

fetch('https://mywebsite.com/endpoint/', {
  method: 'PUT',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
})
.then((response) => response.json())
.then((responseJson) => {
   alert(responseJson)
})
.catch((error) => {
 console.error(error)
})

参考
参考2

获取

使用React Native支持的fetch api。以下是官方文件的示例。

Fetch根据规格支持PUT

fetch('https://mywebsite.com/endpoint/', {
  method: 'PUT',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})

您可以像上面的答案一样使用PUT。您可能缺少"内容类型":"多部分/表单数据;"。

 const config = {
     method: 'PUT',
     headers: {
       'Accept': 'application/json',
       'Content-Type': 'multipart/form-data;',
       'Authorization': 'Bearer ' + 'SECRET_OAUTH2_TOKEN_IF_AUTH',
     },
     body: data,
    }

此博客文章中的一些详细信息:http://snowball.digital/Blog/Uploading-Images-in-React-Native