vue2上传各种格式的文件

1、使用axios上传文件并显示上传进度

2、简单的示例如下

<template>
  <div>
    <input type="file" ref="fileInput" @change="handleFileChange">
    <button @click="uploadFile">上传文件</button>
    <div v-if="uploadProgress > 0">
      <progress :value="uploadProgress" max="100"></progress>
      <span>{{ uploadProgress }}%</span>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      file: null,
      uploadProgress: 0,
    };
  },
  methods: {
    handleFileChange(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'
        },
        onUploadProgress: (progressEvent) => {
          this.uploadProgress = Math.round(progressEvent.loaded / progressEvent.total * 100);
        }
      }).then(() => {
        console.log('文件上传成功!');
      }).catch((error) => {
        console.error('文件上传失败:', error);
      });
    },
  },
};
</script>

3、在这个例子中,使用了一个<input>元素来让用户选择要上传的文件。当文件选择完毕后,我们将文件保存在组件的file属性中。然后,我们在uploadFile方法中创建一个FormData对象,并将文件附加到该对象中。最后,我们使用Axios的post方法将文件上传到服务器,并在请求中指定multipart/form-data类型的头部。此外,我们还指定了一个onUploadProgress回调函数,以便在上传过程中更新上传进度。

4、onUploadProgress是Axios提供的一个回调函数,用于在上传过程中获取上传进度。当您使用Axios上传文件时,Axios会将上传进度作为参数传递给onUploadProgress函数。在这个例子中,我们使用箭头函数来定义onUploadProgress函数,该函数接收一个progressEvent参数,该参数包含有关上传进度的信息。

progressEvent对象有两个属性:loadedtotalloaded表示已上传的字节数,total表示要上传的总字节数。我们可以使用这些属性来计算上传进度的百分比,并将其保存在组件的uploadProgress属性中。在这个例子中,我们使用了Math.round函数来将上传进度四舍五入为整数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值