简体   繁体   中英

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.

      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:

{
  "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.

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. You need to create a new FormData instance, and append data to it. In your case, you want to send the result.uri with the key file , this can be done using formData.append('file', result.uri) . Then you gotta send the formData instance as your body (with method as POST, in your case)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM