【问题标题】:How can I POST an image to DB via react native with the fetch API?如何通过使用 fetch API 做出本机反应将图像发布到数据库?
【发布时间】:2021-09-24 23:29:04
【问题描述】:

所以我试图通过 React Native 和 fetch API 将图像发布到服务器。

      fetch(`${API}/uploadAvatar`, {
        method: "POST",
        headers: {
          Authorization: bearer,
          "X-Requested-With": "XMLHttpRequest",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ file: result.uri }),
      })
        .then((response) => response.json())
        .then((json) => {
          console.log({ json });
          // this console.log outputs:
          // "The format of the file should be jpg, png, jpeg.",
        })
        .catch((err) => {
          console.log({ err });
        });
    }

result 返回:

{
  "cancelled": false,
  "height": 1776,
  "type": "image",
  "uri": "file:///var/mobile/Containers/Data/Application/18F84F29-CB72-4615-A68F-A00422D9B119/Library/Caches/ExponentExperienceData/%2540heythere%252Fkeep-up/ImagePicker/959E8BDE-FCF4-40C6-AF18-8F9EA852760D.jpg",
  "width": 1776,
}

这些是 POSTMAN 上的调用,您可以在其中看到它们的工作原理。

我做错了什么?

【问题讨论】:

  • 真正有帮助的是,如果您去 Postman 并单击“Cookie”旁边和“保存”按钮下方的“代码”。选择 JavaScript Fetch 并查看 sn-p 是否有您的代码没有的内容。

标签: javascript reactjs react-native ecmascript-6 fetch


【解决方案1】:

您的邮递员表明您正在使用表单数据来上传图像,但在您的代码中,您只是在进行 JSON 发布调用而不发送任何表单数据。您需要创建一个新的FormData 实例,并将数据附加到它。在您的情况下,您想使用密钥file 发送result.uri,这可以使用formData.append('file', result.uri) 完成。然后您必须将 formData 实例作为您的主体发送(在您的情况下,方法为 POST)

   let formData = new FormData();
   formData.append('file', result.uri);

   fetch("api/SampleData", {
       body: formData,
       method: "post"
     }).then((response) => response.json())
     .then((json) => {
       console.log({
         json
       });
     })
     .catch((err) => {
       console.log({
         err
       });
     });

【讨论】:

    【解决方案2】:

    您可以在表单数据的帮助下通过创建文件路径、文件名和文件类型的 JSON 对象并将对象附加到带有参数的表单数据实例中来将图像发布到服务器。文件的路径是特定于平台的,因此您必须为路径添加条件。请参考代码sn-p。

    let Data = new FormData();
    Data.append('file',
    { 
    uri: Platform.OS === 'android' ? result.uri: result.uri.replace('file://',''),
    type: result.type,
    name: result.uri.replace(/^.*[\\\/]/, '')
    });
    fetch("api/SampleData", {
       body: Data,
       method: "post",
       headers: {'Content-Type': 'multipart/form-data'}
     }).then((response) => response.json())
     .then((json) => {
       console.log({
         json
       });
     })
     .catch((err) => {
       console.log({
         err
       });
     });
    

    【讨论】:

      猜你喜欢
      • 2019-06-15
      • 2015-08-20
      • 1970-01-01
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 2018-06-25
      相关资源
      最近更新 更多