用vue3写一个文件上传的功能
首先需要安装vue3和axios:
npm install vue@next axios
然后在组件中引入axios:
import axios from 'axios';
下面是一个简单的文件上传组件:
<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('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
},
},
};
</script>
在上面的代码中,我们首先在data中定义了一个file对象,用来保存选中的文件。当用户选择文件的时候,我们通过@change事件来调用handleFileUpload方法,将选中的文件保存到file对象中。当用户点击上传文件按钮时,我们通过axios.post方法来向后端发送一个POST请求,将文件上传到指定的接口。我们使用FormData来创建一个表单数据对象,然后将选中的文件添加到formData中。最后,我们需要设置请求头的Content-Type为multipart/form-data,表示我们要上传的是一个文件。请求成功后,我们可以通过response.data来获取后端返回的数据,请求失败时可以通过catch方法来打印错误信息。
原文地址: https://www.cveoy.top/t/topic/L8p 著作权归作者所有。请勿转载和采集!