Home > other >  How to Upload Image File To server in react native
How to Upload Image File To server in react native

Time:10-10

By selecting Image or File Gallery My data Look Like this

[{"fileCopyUri": "content://com.android.providers.media.documents/document/image:55539", "name": "c6235fa2-aa7f-4e06-a664-7e805de2f883.jpg", "size": 1967925, "type": "image/jpeg", "uri": "content://com.android.providers.media.documents/document/image:55539"}]

{"fileCopyUri": "content://com.android.providers.media.documents/document/document:55435", "name": "Maha Police-2019 222.pdf", "size": 302194, "type": "application/pdf", "uri": "content://com.android.providers.media.documents/document/document:55435"}

By Capturing Image from Camera My data look like this

{"assets": [{"fileName": "rn_image_picker_lib_temp_c96a3333-f53f-4143-af29-e0270c8e6a8c.jpg", "fileSize": 24925, "height": 550, "type": "image/jpeg", "uri": "file:///data/user/0/com.sanayaapp/cache/rn_image_picker_lib_temp_c96a3333-f53f-4143-af29-e0270c8e6a8c.jpg", "width": 247}]}

I am Sending Data through FormData like this


const formData = new FormData();


formData.append('SellerBrandsWeDeal', selectedFile);

fetch('http://api', {
          method: 'POST',
          headers: {Accept: '*/*', 'Content-Type': 'multipart/form-data'},
          body: formData,
})

But its keep saying network error. please help thanks

CodePudding user response:

you can use rn-fetch-blob to code yours picture in base64 string , then you can send base64 string to server. Like this - React-Native: Convert image url to base64 string

CodePudding user response:

You can create image object like this:

    selectedFile = {
                   uri:
"content://com.android.providers.media.documents/document/image:55539",
                    name: "c6235fa2-aa7f-4e06-a664-7e805de2f883.jpg",
                    type: "image/jpeg"
                     }

CodePudding user response:

For me I convert the image to base64 and upload it to the data base as a blob. Here a function to convert it to base64 , all you need is to implement it . The result of the conversion it stored in image state .

const handleFile = (e) => {
let file = e.target.files[0];
getBase64(file)
  .then((result) => {
    // console.log("result",result)
    setImage({
      base64URL: result,
    });
  })
  .catch((err) => {
    setUploadFileError(err);
  });

};

  • Related