用vue3写一个文件上传
时间: 2024-03-09 19:20:41 浏览: 22
好的,我可以为您提供一些关于使用 Vue 3 写一个文件上传的信息。
首先,需要在 HTML 中添加一个文件选择器,例如:
```html
<template>
<input type="file" ref="fileInput" />
</template>
```
然后,在 Vue 组件中,您可以使用 ref 访问文件选择器,并使用它来获取选择的文件:
```javascript
import { ref } from 'vue';
export default {
setup() {
const fileInput = ref(null);
// 获取选择的文件
const file = fileInput.value.files[0];
}
}
```
接下来,您可以使用 FormData 对象将文件发送到服务器,例如:
```javascript
import { ref } from 'vue';
export default {
setup() {
const fileInput = ref(null);
async function uploadFile() {
const file = fileInput.value.files[0];
// 创建 FormData 对象
const formData = new FormData();
// 将文件添加到 FormData 中
formData.append('file', file);
try {
// 使用 axios 将文件发送到服务器
const response = await axios.post('/upload', formData);
console.log(response.data);
} catch (error) {
console.error(error);
}
}
}
}
```
希望这些信息对您有帮助。