vue文件上传与显示

本文详细介绍了Vue.js中利用input[type=file]组件进行文件上传的原理,并结合FormData对象进行数据封装,讲解了如何实现文件上传并显示的完整流程。通过链接提供了深入的技术解析,帮助开发者掌握这一关键功能。
摘要由CSDN通过智能技术生成
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Vue3的Composition API来实现文件上传显示上传进度。以下是一个简单的示例: 首先,你需要在Vue组件中引入`ref`和`onMounted`方法: ```javascript import { ref, onMounted } from 'vue'; ``` 然后,在组件中定义一个`ref`变量来存储上传的文件和上传进度: ```javascript const file = ref(null); const progress = ref(0); ``` 接下来,你需要编写一个方法来处理文件上传,并更新进度: ```javascript function uploadFile() { // 创建FormData对象 const formData = new FormData(); formData.append('file', file.value); // 创建XMLHttpRequest对象 const xhr = new XMLHttpRequest(); // 监听上传进度 xhr.upload.addEventListener('progress', (event) => { if (event.lengthComputable) { progress.value = Math.round((event.loaded / event.total) * 100); } }); // 监听上传完成事件 xhr.addEventListener('load', () => { // 上传完成后的处理逻辑 console.log('上传完成'); }); // 发送请求 xhr.open('POST', '/upload'); xhr.send(formData); } ``` 最后,在组件的模板中添加一个文件选择器和一个上传按钮,并绑定相关的事件: ```html <template> <div> <input type="file" @change="file = $event.target.files[0]"> <button @click="uploadFile">上传</button> <div v-if="progress > 0">上传进度: {{ progress }}%</div> </div> </template> ``` 完整的组件代码如下: ```javascript import { ref, onMounted } from 'vue'; export default { setup() { const file = ref(null); const progress = ref(0); function uploadFile() { const formData = new FormData(); formData.append('file', file.value); const xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', (event) => { if (event.lengthComputable) { progress.value = Math.round((event.loaded / event.total) * 100); } }); xhr.addEventListener('load', () => { console.log('上传完成'); }); xhr.open('POST', '/upload'); xhr.send(formData); } return { file, progress, uploadFile }; } }; ``` 这样,当用户选择文件并点击上传按钮,文件将被上传到服务器,并且上传进度将实显示在页面上。请注意,你需要将`/upload`替换为实际的上传接口地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值