parm530
1/21/2020 - 8:55 PM

Multiple file uploads and JS fetch

Multiple File Uploads Feature (No jQuery!)

  • Documentation
  • Key thing to remember with rails and using the fetch api call:
    • You may need to obtain the csrf token when submitting the form
    • Need to properly prepare the body of the date to be sent with the correct params name
    • FormData is used to send the files to the action properly when using an Uploader class
    • WHEN USING FORM DATA, DO NOT INCLUDE A CONTENT-TYPE HEADER IN YOUR REQUEST!
function getMetaValue(name) {
    // Alternative to obtaining the CSRF token ---> Rails.csrfToken()
    let element = document.head.querySelector(`meta[name="${name}"]`);
    return element.getAttribute("content");
}

function uploadFile(data, file, counter) {
// let data = new FormData();
    data.append('product_image[image]', file);
    data.append('product_image[title]', file.name);

    fetch('/summit/products/' + prodId + '/product_images', {
        method: 'POST',
        body: data,
        credentials: "same-origin",
        mode: 'cors',
        headers: {
            'X-CSRF-Token': getMetaValue("csrf-token")
        }
    })
    .then((result) =>  {
        acknowledgeUpload(counter);
        progressDone();
    })
    .catch((error) => {
        alert("Something went wrong, please contact contact your admin for support")
    });
}

NOTE

fetch does not handle FAILED HTTP codes/does not reject a promise unless a network error occurs!

This means you will need to handle your errors in a different way:

function handleError(response) {
  if (!response.ok) {
    throw Error(response.textStatus)
  }
  
  return response.text();
}


fetch()
.then(handleErrors)
.then(() => {
  // code
})
.catch((error) => {
  // more code to alert the user of error
)