【问题标题】:Upload Image to server with React-Native使用 React-Native 将图像上传到服务器
【发布时间】:2021-12-31 17:30:36
【问题描述】:

我的名字是里奥。我正在尝试将头像上传到服务器。我发现大家都是用Formdata来上传的。但在我的情况下,我需要 2 个表单数据(avt、电子邮件)键,所以我该如何处理。非常感谢!

这是我在 Postman 中的测试

【问题讨论】:

  • 您使用的是哪个邮递员版本?最新版本(9.1.5)会自动为每个键值对添加content-type,或许可以解决你的问题。

标签: react-native api postman form-data avatar


【解决方案1】:

对于您的用例,您可以构建formData,例如:

let data = new FormData();
data.append('avt', {
  name: '<file_name>',
  type: '<file_type>', // e.g. 'image/png'
  uri: '<file_uri>',
});

data.append('email', 'test@email.com');

如果您使用fetch 发出 API 请求,那么您的请求可以是:

fetch('<api_url>', {
  method: '<api request method>',
  body: data,
  headers: {
    'Content-Type': 'multipart/form-data',
    // ...other headers
  }
})
  .then((response) => response.json())
  .then((response) => {
    console.log('upload file response: ', response)
  })
  .catch(() => {
    console.log('upload file error: ', error);
  });

如果您使用axios 发出 API 请求,那么您的请求可以是:

axios({
  url: '<api_url>',
  method: '<api request method>',
  data: data,
})
  .then((response) => {
    console.log('upload file response: ', response)
  })
  .catch(() => {
    console.log('upload file error: ', error);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-01
    • 2021-05-29
    • 2020-09-07
    • 2020-02-15
    • 2019-10-27
    • 2019-03-20
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多