gpt4 book ai didi

javascript - 如何在VueJs中上传不同字段的多张图片?

转载 作者:行者123 更新时间:2023-12-03 01:19:46 27 4
gpt4 key购买 nike

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。如何使用 photoA、photoB 和 photoC 执行 axios.post ?如何获取 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

关于javascript - 如何在VueJs中上传不同字段的多张图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51808554/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com