I was working on React Native and had to write a api to send image back to server using HTML5 Fetch API. The process is straight forward.

I’m using Python Django with Django REST Framework for api, so its just a basic REST endpoint and FormData, the FormData provides an easy method to construct a set of key/value pairs representing form fields and their values, which can then be easily sent over using api request.

I have used an image picker literary which on selection returned an object with image location, file name, type, size and other meta informations. We will requiring the file location, file type and name for the upload to succeed.


var formData = new FormData();
// Fields in the post
formData.append("id", "");

// pictureSource is object containing image data.

if (pictureSource) {
  var photo = {
    uri: pictureSource.uri,
    type: pictureSource.type,
    name: pictureSource.fileName,
  };
  formData.append('scannedrecord_1', photo);
}

Using the image information create photo object and append to form data, this wraps the initial tasks now lets fire up a fetch request to server and get the image out.


fetch(  + '/user/' + , {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'multipart/form-data',
    'Authorization': 
  },
  body: formData
 })
.then((response) => response.json())
.then((responseJson) => {
  // Perform success response.
  console.log(responseJson);
 }   
})
.catch((error) => {
    console.log(error)
    postSubmit(["Ops, something Went Wrong."]);
});