Search code examples
vue.jsfor-loopmultipartform-dataform-data

How to Loop Through formData & POST requests


I'm trying to make a post request each time one of the files I have in 'this.photos' is appended to formData. Right now, I have the correct number of API calls being made, but they're all just the last photo uploaded being repeated.

My Backend doesn't allow for multiple items in one field, so I need to make as many API calls as there are files added on the frontend

<template>
  <div class="container">
    <div class="large-12 medium-12 small-12 cell">
      <label>
        Files
        <input type="file" id="files" ref="photos" multiple v-on:change="handleFilesUpload()" />
      </label>
      <button v-on:click="submitFiles()">Submit</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      photos: ""
    };
  },

  methods: {
    submitFiles(axios) {
      //let formData = new FormData();
      for (var i = 0; i < this.photos.length; i++) {
        let formData = new FormData();
        let photo = this.photos[i];

        formData.append("photos", photo);
        const config = {
          headers: {
            "content-type": "multipart/form-data; "
          }
        };
        this.$axios
          .post(`/api/v1/photos/`, formData, config)
          .then(response => {
            console.log("Successfully Submitted Images");
          })
          .catch(error => {
            console.log(error);
          });
      }
    },

    handleFilesUpload() {
      this.photos = this.$refs.photos.files;
      console.log(this.photos);
    }
  }
};
</script>

I feel like it's just something simple that I'm missing 😖, so thanks for the help!


Solution

  •   //let formData = new FormData();
          for (var i = 0; i < this.photos.length; i++) {
            let formData = new FormData();
    

    Fix: Move the formData declaration inside of the for loop. If it's outside, the final photo gets queued 3 times before being posted. The fix makes sure only the photo in question is queued and sent