vue实现单文件上传
单文件上传实现步骤
使用Vue实现单文件上传可以通过<input type="file">结合FormData完成。以下是具体实现方式:

模板部分
在Vue组件模板中添加文件输入框和上传按钮:

<template>
<div>
<input type="file" @change="handleFileChange" ref="fileInput" />
<button @click="uploadFile">上传文件</button>
<p v-if="uploadStatus">{{ uploadStatus }}</p>
</div>
</template>
脚本部分
在Vue组件的<script>中实现文件选择和上传逻辑:
<script>
export default {
data() {
return {
selectedFile: null,
uploadStatus: ''
}
},
methods: {
handleFileChange(event) {
this.selectedFile = event.target.files[0]
},
async uploadFile() {
if (!this.selectedFile) {
this.uploadStatus = '请先选择文件'
return
}
const formData = new FormData()
formData.append('file', this.selectedFile)
try {
const response = await fetch('你的上传接口URL', {
method: 'POST',
body: formData
})
if (response.ok) {
this.uploadStatus = '文件上传成功'
this.$refs.fileInput.value = '' // 清空文件选择
} else {
this.uploadStatus = '文件上传失败'
}
} catch (error) {
this.uploadStatus = '上传过程中出现错误'
console.error(error)
}
}
}
}
</script>
样式部分(可选)
添加基本样式改善用户体验:
<style scoped>
input[type="file"] {
margin: 10px 0;
}
button {
padding: 8px 16px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
</style>
关键点说明
- 使用
FormData对象构建表单数据,适合文件上传场景 fetchAPI发送POST请求,也可替换为axios等HTTP库- 文件选择通过
@change事件监听,获取event.target.files[0] - 上传状态通过
uploadStatus数据属性反馈给用户 - 上传成功后清空文件选择框的值
服务器端注意事项
- 后端接口需要支持
multipart/form-data格式 - 可能需要设置请求头
Content-Type: multipart/form-data - 根据业务需求添加文件大小、类型等验证逻辑
以上实现可以扩展添加进度显示、文件预览等功能,满足不同业务场景需求。






