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

时间:2016-04-03 01:32:29

标签: javascript curl file-upload xmlhttprequest react-native

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

我发现XMLHttpRequest method在浏览器上执行此操作但不适用于react-native。有人经历过这个请帮助!!!

3 个答案:

答案 0 :(得分:1)

使用React Native支持的fetch api。 以下是official documentation

的示例

根据specs提取支持PUT

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

答案 1 :(得分: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

答案 2 :(得分:0)

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

reference
 reference 2