简体   繁体   English

如何通过使用 fetch API 进行本机反应将图像发布到数据库?

[英]How can I POST an image to DB via react native with the fetch API?

So I am trying to POST an image to a server via React Native and the fetch API.所以我试图通过 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 returns this: 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,
}

Those are the calls on POSTMAN where you can see they work.这些是对 POSTMAN 的调用,您可以在其中看到它们的工作情况。

What am I doing wrong?我究竟做错了什么?

在此处输入图片说明

在此处输入图片说明

Your postman shows that you're using form-data to upload the image, but in your code you're simply making a JSON post call without sending any form-data.您的邮递员显示您正在使用表单数据上传图像,但在您的代码中,您只是进行 JSON 发布调用而不发送任何表单数据。 You need to create a new FormData instance, and append data to it.您需要创建一个新的FormData实例,并向其追加数据。 In your case, you want to send the result.uri with the key file , this can be done using formData.append('file', result.uri) .在您的情况下,您希望将result.uri与密钥file一起发送,这可以使用formData.append('file', result.uri) Then you gotta send the formData instance as your body (with method as POST, in your case)然后你必须将 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
       });
     });

You can post images to the server with the help of Form Data by creating a JSON object of the file path, file name, and file type and append the object into the Form Data instance with the parameter.您可以通过创建文件路径、文件名和文件类型的 JSON 对象,并使用参数将该对象附加到 Form Data 实例中,在 Form Data 的帮助下将图像发布到服务器。 The path of the file is Platform-specific therefore you have to add conditions for the path.该文件的路径是特定于平台的,因此您必须为路径添加条件。 Please refer to the code snippet.请参考代码片段。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在获取请求中传递 POST 参数? - 反应本机 - How can I pass POST parameters in fetch request? - React Native 如何通过邮寄将图像二进制文件发送到 API? 节点 - how can I send an image binary via post to an API? nodejs 如何在 React Native 中通过 GET 请求获取图像? - How to fetch image via GET request in React Native? React Native - 我无法从我的 FETCH 中得到响应,但我的 api 确实获取了我发布的数据 - React Native - I can't get a response from my FETCH, but my api does get the data i post 如何在React Native上使用访存功能登录API并捕获登录错误? - How can I log in to an API and catch login errors using fetch on React Native? 如何从通过 Fetch API 发送的后端 (localhost) 获取数据? (PHP、Fetch、React Native、POST 请求) - How do I fetch data from my back-end (localhost) that's being sent through Fetch API? (PHP, Fetch, React Native, POST request) 我如何通过 id 在 react native (rest api) 上获取数据 - how do i fetch data by id on react native (rest api) 我可以在我的 console.log 中显示 API 数据,但我不能用它来设置状态。 . . 我该如何设置状态? (获取,反应本机) - I could display API data in my console.log, but I can't setState with it . . . how can I setState? (fetch, React Native) 如何使用fetch in native native发布表单? - How to post a form using fetch in react native? 通过 Fetch React Native Post Request 引发网络请求失败 - React Native Post Request via Fetch throws Network Request Failed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM