如何在VueJs中从不同字段上传多个图像?

时间:2018-08-12 11:49:36

标签: javascript vue.js

vuejs文件

<v-form method="post" enctype="multipart/form-data">
            <div v-if="!loading">
            <v-card-text headline><h1>Please upload your documents</h1></v-card-text>
            <v-layout row class="pt-1">
              <v-flex xs12>
                <v-subheader>Photo A</v-subheader>
              </v-flex>
              <v-flex xs12>
                <input id="photoA" type="file" accept="image/*">
              </v-flex>
            </v-layout>
            <v-layout row>
              <v-flex xs12>
                <v-subheader>Photo B</v-subheader>
              </v-flex>
              <v-flex xs12>
                <input id="photo B" type="file" accept="image/*">
              </v-flex>
            </v-layout>
            <v-layout row>
              <v-flex xs12>
                <v-subheader class="text-sm-left">Photo C Statement</v-subheader>
              </v-flex>
              <v-flex xs12>
                <input id="photoC" type="file" accept="image/*">
              </v-flex>
            </v-layout>
            <div v-html="error" />
            <div>
              <v-btn round block color="blue darken-3" dark large @click="submitDocs">Upload</v-btn>
            </div>
            </div>
          </v-form>

脚本

submitDocs () {
  console.log("submit docs clicked!")
  const formData = new FormData()
  formData.append('myFile', this.selectedFile, this.selectedFile.name)
  axios.post('my-domain.com/file-upload', formData)
}

我坚持写submitDocs。我如何将axios.post与photoA,photoB和photoC配合使用?如何获取photoA,photoB和photoC的文件并通过axios.post上传?先感谢您。

1 个答案:

答案 0 :(得分:1)

v-model不支持

input[type=file],因此您需要为每个输入编写自己的处理程序:

<input id="photoA" type="file" accept="image/*" @change="addFile('photoA', $event)">
...
<input id="photoA" type="file" accept="image/*" @change="addFile('photoB', $event)">
...
<input id="photoA" type="file" accept="image/*" @change="addFile('photoC', $event)">

处理程序的实现可能如下所示:

methods: {
  addFile(fileKey, event) {
    this[fileKey] = event.target.files[0];
    console.log('File added', fileKey, event.target.files[0]);
  },
}

将每个文件追加到FormData

const formData = new FormData()
formData.append('photoA', this.photoA, this.photoA.name)
formData.append('photoB', this.photoB, this.photoB.name)
formData.append('photoC', this.photoC, this.photoC.name)
axios.post('my-domain.com/file-upload', formData)

但是,只有当您有几张照片时,这种方法才是好的。如果您想将其用于许多图像,最好将其存储在数组中。例如

const formData = new FormData();
// let's say you have array of files in your `this.photos`
this.photos.map(photo => formData.append('photos[]', photo, photo.name);
axios.post('my-domain.com/file-upload', formData)

简单的演示在这里https://codesandbox.io/s/kx7y3knvjr