Uploading Image using fetch api and FormData

How to perform a image upload using Javascript Fetch API and FormData

Advert

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", "<UNIQUE_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( <API_URL> + '/user/' + <URL_ID>, {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'multipart/form-data',
    'Authorization': <AUTH TOKEN>
  },
  body: formData
 })
.then((response) => response.json())
.then((responseJson) => {
  // Perform success response.
  console.log(responseJson);
 }   
})
.catch((error) => {
    console.log(error)
    postSubmit(["Ops, something Went Wrong."]);
});

Comments

Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ rel="nofollow" for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.

Last 5 Articles

All Articles >

  1. 3 Money-Saving Tips For Your Company

     
  2. Domain Authority

     
  3. Public Endpoint in Django Rest Framework

     
  4. 4 Ways to Increase Conversion Rates using Videos

     
  5. Getting the best customer experience analytics solutions

     

News Letter

Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.