Skip to content Skip to sidebar Skip to footer

Multipart/form-data Form With No Field Names

I have an HTML form that I was using to send information to the nodejs backend. I then tried to implement file uploads using the same form. To do that, I had to change the enctype

Solution 1:

You can use FormData to set key and value multipart/form-data, fetch() or XMLHttpRequest() to POST data to server.

<formid="form"><select><optionvalue="1">1</option><optionvalue="2">2</option></select><inputtype="file" /><inputtype="submit"value="Submit" /></form>

functionsubmitRequest(event) {
  event.preventDefault();
  var i = 0;
  var inputs = form.querySelector("input[type=file], select");
  var fd = newFormData();
  for (let el of inputs) {
    if (el.tagName === "SELECT") {
      fd.append("select", el.value)
    }
    if (el.type === "file") {
      if (el.files.length) {
        for (let file of el.files) {
          fd.append("file" + (i++), file);
        }
      }
    }
  }
  fetch("/path/to/server", {method:"POST", body:fd})
  .then(function(response) {
    return response.text()
  })
  .then(function(res) {
    console.log(res)
  })
  .catch(function(err) {
    console.log(err)
  })
}

const form = document.getElementById("form");
form.onsubmit = submitRequest;

Post a Comment for "Multipart/form-data Form With No Field Names"