如果你想记住用户选择的文件对象,你可以使用这个javascript:
new Vue({
el: '#app',
data() {
return {
files: [],
filesAccumulated: []
}
},
methods: {
onChange(event) {
this.files.forEach(thisFile => {
this.filesAccumulated.push(thisFile)
})
},
onReset() {
this.filesAccumulated = []
}
}
})
一起使用这个 vue 模板
<div id="app">
<b-form-file
v-model="files"
multiple plain
v-on:input="onChange">
</b-form-file>
<div>
<ul>
<li v-for="thisFile in filesAccumulated">
{{ thisFile.name }}
</li>
</ul>
</div>
<b-button v-on:click="onReset">
Reset
</b-button>
</div>
当用户执行选择时,b-form-file vue 组件会发出input 事件。可以拾取文件对象
来自与v-model 指令绑定的变量。见documentation
看看这个小提琴https://jsfiddle.net/1xsyb4dq/2/,看看代码在起作用。
一般cmets
让我在你的代码示例和 b-form-file 组件上做一些 cmets:使用 bootstrap-vue 和 <b-form-file> 不建议使用封闭的表单标签来提交表单。相反,您使用 vue 的 v-model 功能从 vue 的数据对象中获取 file objects。
我在这里创建了一个更全面的例子https://jsfiddle.net/to3q7ags/,但我会一步一步解释:
v-model 属性的值是一个 vue 数据属性的名称:
<b-form-file v-model="files" multiple plain></b-form-file>
用户在文件输入字段中点击“浏览”,选择文件并按下确定后,vue data 属性将保存一个文件对象数组:
new Vue({
el: '#app',
data() {
return {
files: []
// initially empty, but will be populated after file selection
}
}
})
来自b-form文件documentation:
当没有选择文件时,将返回一个空数组。当一个
选择一个或多个文件,返回值将是一个数组
JavaScript 文件对象实例。
用户选择文件后,您可以通过单击按钮或更改事件将文件发送到您的服务器。
<b-button v-on:click="onSubmit">
Submit
</b-button>
对应的vue方法是这样的
methods: {
onSubmit() {
// Process each file
this.files.forEach(thisFile => {
console.log("Submitting " + thisFile.name)
// add submit logic here
}
}
要提交文件,您需要手动创建一个使用multipart/form-data 编码的http post 请求。这可以通过使用FormData 类来完成。
const formBody = new FormData()
formBody.set("formParameter", thisFile)
FormData.set() 方法接受文件 blob 作为参数。然后你可以使用 XMLHttpRequest.send() 或 fetch() 来发送 post 请求:
fetch(
"https://yourserver/post",{
method: 'POST',
body: formBody})
.then(response => console.log(response))
现在所有选定的文件都已发布到服务器。用户可以使用相同的表单重复该过程,选择新的文件集并再次按下发布按钮。
您还可以通过侦听“输入”事件来自动发送表单,而无需使用按钮。拖放也可以。