vue3实现文件上传下载
时间: 2023-09-11 12:07:11 浏览: 132
在 Vue 3 中实现文件上传和下载,你可以按照以下步骤进行操作:
1. 文件上传:
- 首先,你需要在你的 Vue 组件中添加一个文件上传的 `<input>` 元素。可以使用 `v-model` 指令绑定一个数据属性来获取用户选择的文件。
- 添加一个事件处理函数,当用户选择文件时触发。在该函数中,你可以使用 `FormData` 对象来创建一个表单数据对象,并将文件添加到其中。
- 使用 Axios 或其他 HTTP 请求库,将表单数据对象发送到服务器。
下面是一个示例代码:
```vue
<template>
<div>
<input type="file" @change="handleFileUpload" />
<button @click="uploadFile">上传文件</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
file: null,
};
},
methods: {
handleFileUpload(event) {
this.file = event.target.files[0];
},
uploadFile() {
const formData = new FormData();
formData.append('file', this.file);
axios.post('/upload', formData)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
},
},
};
</script>
```
2. 文件下载:
- 在你的 Vue 组件中,添加一个按钮或链接,用于触发文件下载操作。
- 添加一个事件处理
阅读全文
相关推荐
















