簡體   English   中英

如何在VueJs中從不同字段上傳多個圖像?

[英]How to upload multiple images from different fields in VueJs?

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上傳? 先感謝您。

input[type=file]不支持v-model因此您需要為每個輸入編寫自己的處理程序:

<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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM