Netlify forms file upload using Vue/Gridsome

Hi,

I have been researching and trying for several days how to upload a file in a Netlify form using Vue (in this case Gridsome, but I don’t think it makes much of a difference). I can see all of the text data from the other form inputs, so I know the form is setup properly. The only thing missing from my submissions is the download link to the uploaded files. The field is there, but there isn’t any data with it. In fact, the files do not get uploaded at all, since I can see in my usage that I have 0kb uploaded so far, despite the repeated tests I submitted.

Here is the relevant html code:

 <form
        id="sign-up"
        class="form"
        name="sign-up"
        method="POST"
        netlify-honeypot="bot-field"
        data-netlify="true"
        novalidate
        enctype="multipart/form-data"
        @submit.prevent="submit"
      >
 <label for="files">
            Add file
            <input
              id="files"
              type="file"
              name="files"
              @change="processFile($event)"
            />
      </label>
        <input
          type="submit"
          value="Submit"
          class="submit"
          :disabled="submitStatus === 'PENDING'"
          :aria-disabled="submitStatus === 'PENDING'"
        />
</form>

And here is the relevant JS code:

  data() {
    return {
      formData: {},
    };
  },
methods: {
processFile() {
  this.formData.files = event.target.files;
},
encode(data) {
  const formData = new FormData();
  for (const key of Object.keys(data)) {
    formData.append(key, data[key]);
  }
  return formData;
},
submit(e) {
    fetch("/", {
      method: "POST",
      body: this.encode({
        "form-name": e.target.getAttribute("name"),
        ...this.formData
      })
    })
      .then(res => {
        res.json();
      })
      .catch(err => alert(err));
  }
}
  }

I can’t figure out where I went wrong, can anybody help me out?

Thanks

Hi, before we get further into troubleshooting, did you read/work through these threads already?

Yes I did. I actually based by code on these examples, hence why I absolutely don’t understand why I’m not getting the files in the submissions. Maybe I missed something?

I finally made it work! Turns out I wasn’t appending the file properly to the FormData object. I re-wrote my encode function as this:

    encode(data) {
  const formData = new FormData();
  for (const key of Object.keys(data)) {
    if (key === "files") {
      formData.append(key, data[key][0]);
    } else {
      formData.append(key, data[key]);
    }
  }
  return formData;
}
3 Likes

thanks for sharing!!

Legend, tried 10 different solutions, most from netlify forum and none worked, except this.

1 Like