vue上传多文件到服务器
时间: 2023-10-04 12:11:43 浏览: 38
你可以使用 HTML5 的 FormData 对象来上传多文件到服务器,以下是一个简单的示例代码:
HTML 代码:
```html
<template>
<div>
<input type="file" multiple @change="handleFileChange">
<button @click="uploadFiles">上传</button>
</div>
</template>
```
Vue.js 代码:
```javascript
<script>
export default {
data() {
return {
files: [] // 保存选中的文件
}
},
methods: {
handleFileChange(event) {
this.files = event.target.files
},
uploadFiles() {
const formData = new FormData()
for (let i = 0; i < this.files.length; i++) {
formData.append('files', this.files[i])
}
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
// 处理上传成功的响应
}).catch(error => {
// 处理上传失败的响应
})
}
}
}
</script>
```
在上面的代码中,我们监听了文件选择框的 change 事件,将选中的文件保存到 files 数组中。然后在上传文件按钮被点击时,我们使用 FormData 对象构建了一个表单数据,将选中的文件加入到其中,并使用 axios 库发送了一个 POST 请求到服务器的 /upload 路径。在请求头中设置了 Content-Type 为 multipart/form-data,这是因为我们要上传的是二进制文件而不是 JSON 数据。
注意,上面的示例代码使用了 axios 库来发送 HTTP 请求,如果你使用的是其他库,可能需要做些适当的调整。