在React Native中使用PUT方法上传文件

4

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

我在这里找到了在浏览器上执行此操作的XMLHttpRequest方法,但无法在react-native上工作。有没有人经历过这个,请帮忙!!!

3个回答

2
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)
})

参考文献
第二个参考文献


0

获取

使用由React Native支持的获取API。 以下是官方文档的示例。

根据规格,获取支持PUT

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

你提供的例子是POST方法,我期望看到PUT方法的例子。我已经查阅了规范并知道fetch支持PUT方法。 - Susth
问题是关于上传文件的。 - Caio Iglesias

0

您可以像上面的答案一样使用PUT。您可能错过了 'Content-Type': 'multipart/form-data;'。

 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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接