使用vue和fetch进行文件上传怎么写
时间: 2023-01-11 13:55:36 浏览: 90
首先,需要在 HTML 中添加一个文件选择器和一个提交按钮。
```html
<template>
<form>
<input type="file" ref="fileInput" />
<button type="submit">上传</button>
</form>
</template>
```
然后,在 Vue 组件的 JavaScript 部分中,可以使用 fetch 函数发送文件到服务器。首先,需要获取文件对象,然后创建一个 FormData 对象,并将文件添加到 FormData 中。
```javascript
<script>
export default {
methods: {
async uploadFile() {
// 获取文件对象
const file = this.$refs.fileInput.files[0]
// 创建 FormData 对象
const formData = new FormData()
// 将文件添加到 FormData 中
formData.append('file', file)
try {
// 使用 fetch 发送文件到服务器
const res = await fetch('/upload', {
method: 'POST',
body: formData
})
console.log(await res.json())
} catch (err) {
console.error(err)
}
}
}
}
</script>
```
最后,在表单提交事件中调用上传文件函数。
```html
<template>
<form @submit.prevent="uploadFile">
<input type="file" ref="fileInput" />
<button type="submit">上传</button>
</form>
</template>
```
这样就可以使用 Vue 和 fetch 进行文件上传了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)