如何循环遍历 formData 和 POST 请求

How to Loop Through formData & POST requests

每次我在 'this.photos' 中的文件之一附加到 formData 时,我都试图发出 post 请求。现在,我有正确数量的 API 调用,但它们都只是重复上传的最后一张照片。

我的后端不允许在一个字段中包含多个项目,因此我需要进行与前端添加的文件一样多的 API 调用

<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>

我觉得我缺少的只是一些简单的东西,所以感谢您的帮助!

试试这个:

submitFiles(axios) {
let formData = new FormData();
for (var i = 0; i < this.photos.length; i++) {
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);
});
},
  //let formData = new FormData();
      for (var i = 0; i < this.photos.length; i++) {
        let formData = new FormData();

修复:将 formData 声明移到 for 循环内。如果在室外,最终照片在发布前会排队 3 次。该修复确保只有有问题的照片被排队和发送