Unable to add or remove image from multiple html input field
I successfully got this to work using the method described by the author, but I'm using fetch()
instead of jQuery:
document.forms[0].addEventListener("submit", async function (e) {
e.preventDefault();
const url = this.getAttribute("action"); // grab endpoint from HTML
const fd = new FormData(); // create FormData object
upload.cachedFileArray.forEach((file, i) => {
fd.append("files[]", file); // append each file to FormData object
});
this.querySelectorAll("input[name], select, textarea").forEach(el => {
fd.append(el.getAttribute("name"), el.value);
});
const response = await fetch(url, {
method: 'POST',
body: fd
});
// optional processing of server response
const text = await response.text();
console.log('Success:', text);
// what happens after upload here
location = "https://google.com"; // navigate to Google
});
Add this to your script. It intercepts the form submission, creates a FormData
object based on the File array, adds the remaining form fields, then submits it to the url stated it the form's action
attribute.
Note that you should probably remove the name
attribute from the <input type="file">
on the form, since we don't want to add that to the FormData.