如何使用 fetch API 通过 React Native 将图像发布到数据库?

Rea*_*ing 4 javascript fetch ecmascript-6 reactjs react-native

所以我尝试通过 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 });
        });
    }
Run Code Online (Sandbox Code Playgroud)

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,
}
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?

在此输入图像描述

在此输入图像描述

小智 5

您的邮递员显示您正在使用表单数据来上传图像,但在您的代码中,您只是进行 JSON post 调用,而不发送任何表单数据。您需要创建一个新FormData实例,并向其附加数据。result.uri在您的情况下,您想使用密钥发送file,这可以使用 来完成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
       });
     });
Run Code Online (Sandbox Code Playgroud)