API – XmlHttpRequest – Uploading image and Sending using FormData

=> If only the data has to be sent through axios then we can directly use axios.METHOD to send the data to any URL

=> But if only the image/file has to be uploaded or along with data then we must use XMLHttpRequest to send the data+files/images using FormData()

=> Just append the image/file to be sent to formData and we are ready to go.

Point to be Noted

  1. // params received in functions are: URL, METHOD, DATA, FILES, fieldName, isSecure=false
  2. // Inside the body we must write all the code with return new Promise((resolve, reject) => { ………………}}
  3. function UPLOAD(url, method, data, files, keyName, isSecure = false) {return new Promise(){................}}
  4. // Create formData
  5. const formData = new FormData();
  6. // Append all received data into the form
  7. // add each data in formData
        for (let key in data) {
    
          formData.append(key, data[key]);
    
        }
  8. // add each files[] if exist in the fieldName
      if (files && files.length) {
    
          files.forEach(function (file, index) {
    
            formData.append(fieldName, file, file.name);
    
          })
    
        }
  9. // create XMLHttpRequest so that request can be sent to the server using its instance
        const xhr = new XMLHttpRequest();
  10. // Keep track the ready state to be executed on some condition and return promise with resolve and reject

     xhr.onreadystatechange = () => {
    
          if (xhr.readyState === 4) {
    
            if (xhr.status >= 200 && xhr.status <= 210) {
    
              resolve(xhr.response)
    
            } else {
    
              reject(xhr.response)
    
            }
    
          }
    
        }
  11.  // Open XMLHttpRequest instance on method at some url with sync/async=false/true
    xhr.open(method, `${baseUrl}${url}`, true);
  12. // Make sure you set the request header of Content-Type and Authorization before sending the data
    xhr.setRequestHeader("Content-Type", "application/json");
    
    xhr.setRequestHeader("Authorization", `Bearer ${localStorage.getItem('token')}`);     // using token stored in localStorage
  13. // Finally send the formData through instance of XMLHttpRequest
      xhr.send(formData);

COMPLETE CODE

function UPLOAD(url, method, data, files, fieldName, isSecure = false) {

  return new Promise((resolve, reject) => {

    const formData = new FormData();


    // add each data in formData

    for (let key in data) {

      formData.append(key, data[key]);

    }


    if (files && files.length) {

      files.forEach(function (file, index) {

        formData.append(fieldName, file, file.name);

      })

    }

  // send request to server using xml http request
    const xhr = new XMLHttpRequest();
    xhr.onreadystatechange = () => {

      if (xhr.readyState === 4) {

        if (xhr.status >= 200 && xhr.status <= 210) {

          resolve(xhr.response)

        } else {

          reject(xhr.response)

        }

      }

    }

  xhr.setRequestHeader(“Content-Type”, “application/json”);
    if(isSecure){
      xhr.setRequestHeader(“Authorization”, `Bearer ${localStorage.getItem(‘token’)}`);
    }
    xhr.send(formData);

  })

}

 

Leave a Reply

Your email address will not be published. Required fields are marked *