blaziken105
blaziken105

Reputation: 501

Posting Images using formData to a Django Rest API

I have a Django Rest API backend and am using a React Native Front End. I wanted to save an image to the rest API.

The POST method used is as follows:

async saveUserData() {
  let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);

  var formData  = new FormData();
  formData.append("bio",this.state.bio);
  formData.append("website",this.state.website);
  formData.append("phoneno",this.state.phoneno);
  formData.append("gender",this.state.gender);
  formData.append("avatar",this.state.avatar.uri);

   try {
     let response = await fetch(url, {
       method: 'POST',
       headers: {
         'Accept': 'application/json',
         'Content-Type': 'multipart/form-data',
         'Authorization': ' Token '+accessToken,
       },
       body: formData
     });

     let responseJson = await response.text();
     if(response.status>=200&&response.status<300){
        console.log("POST Completed");
     }else{
       let error=responseJson;
       console.log(error);
       throw error;
     }
     return responseJson;
   } catch(error) {
     return error;
     console.error(error);
   }
}

I get the following error {"avatar":["The submitted data was not a file. Check the encoding type on the form."]}

I have also tried this.state.avatar.data and tried to post it but I end up getting the same error. I know that the file upload works fine as I can do it properly from the REST Autogenerated form. What seems to be the problem in the image I am posting?

Upvotes: 1

Views: 2374

Answers (1)

martinarroyo
martinarroyo

Reputation: 9701

Here is how you can do it:

var formData = new FormData();
formData.append('avatar', {uri: this.state.avatar.uri, name: 'yourname.jpg', type: 'image/jpg'});

let response = await fetch(url, {
   method: 'POST',
   headers: {
     'Accept': 'application/json',
     'Content-Type': 'multipart/form-data',
     'Authorization': ' Token '+accessToken,
   },
   body: formData
 });

Upvotes: 3

Related Questions