How to upload an image on django server with react native?

Viewed 39

I'm using react native on frontend and django in backend. I want to submit a form and that form contains images in it. Now the problem is. I'm unable to upload images with following code. currently following json is going in backend.

{
    "details":{
        "name":"My first ",
        "description":"this is Gina be cool",
        "display":"file:///data/user/0/com.merchant_app/cache/rn_image_picker_lib_temp_935cb7c5-72fd-4c7a-ab45-7b62906909f7.jpg",
        "background":"file:///data/user/0/com.merchant_app/cache/rn_image_picker_lib_temp_9449c3c0-32c6-4122-8a92-1a9b5afa352f.jpg"
    },
   "hours":[
      {
         "partition":"P1",
         "timings":[
            {
               "day":"Monday",
               "full_day":false,
               "close_day":false,
               "start_time":"2022-09-16T01:00:00.149Z",
               "close_time":"2022-09-16T01:00:00.149Z"
            }

         ]
      }
   ]
}

backend response :

{'display': ['The submitted data was not a file. Check the encoding type on the form.'], 'background': ['The submitted data was not a file. Check the encoding type on the form.']}

my code .

const {Name,bio,displayFilePath,backgroundFilePath} = this.props.route.params.stepOneData
const background = backgroundFilePath
const display = displayFilePath
console.log("==> ",backgroundFilePath.assets[0].fileName)

let data = {
  details = {
    name:Name,
    description:bio,
    display:display,
    background:background
  },
  hours:[
    {
       "partition":"P1",
       "timings":[
          {
             "day":"Monday",
             "full_day":false,
             "close_day":false,
             "start_time":"2022-09-16T01:00:00.149Z",
             "close_time":"2022-09-16T01:00:00.149Z"
          }

       ]
    }
 ]

}


try {
  await addNewGroundAPI(formdata)
  alert("Post created")

}
catch (e) {
  console.log("Error", e)
  // alert("Error")

}

If you know to fix it. Please contribute in solving this thank You.

1 Answers

Use the following format to pass image object to server

{
    name: //image name,
    type: //image mime can be found at backgroundFilePath.assets[0].mime,
    uri: //image path can be found at backgroundFilePath.assets[0].path,
    size: //image size can be found at backgroundFilePath.assets[0].size,
}

Also, Please make sure you are passing Form data object (new FormData()) to your server.

Related