• Axios如何做文件上传功能
  • 发布于 2个月前
  • 184 热度
    0 评论

前言:

最近有不少初学者在后台留言咨询Axios上传附件的问题,鉴于咨询的同学比较多,我这就简单写了个Axios上传附件的样例代码给大家参考,希望对于初学者有所帮助。


Axios上传附件代码:


<template>
  <div>
    <div>
      选择文件: 
      <input id="myFile" type="file" @change="fileChange" />
    </div>
    <div>
      当前上传进度: <span>{{ currentPercentage + '%' }}</span>
    </div>
    <div>
      <input type="button" value="上传文件/断点续传" @click="uploadFile" />
      <input type="button" value="取消上传" @click="cancelUploadFile" />
    </div>
  </div>
</template>

<script lang="ts">
  import { Vue, Component } from 'vue-property-decorator';

  import axios from 'axios';

  @Component
  export default class Property extends Vue {
    // 堆代码 duidaima.com
    // 当前选中的文件
    file: any = null;

    // 当前选中文件的大小
    fileSize: number = 0;
    // 初始上传偏移量
    startOffset: number = 0;
    // 当前已上传偏移量
    currentOffset: number = 0;
    // 当前已上传百分比进度
    currentPercentage: number = 0;

    // 取消请求的对象
    source: any = null;

    // 选择文件,仅一个
    fileChange(e: any) {
      // 选中的文件
      this.file = e.target.files[0];
      // 选中的文件的大小
      this.fileSize = this.file.size;
    }

    // 开始上传
    uploadFile() {
      // 每次都需要重新生成source, 因为根据source取消上传后, 再用同一个source会造成不会再发起请求
      this.source = axios.CancelToken.source();
      
      // 将文件加入表单中
      let formData = new FormData();
      formData.append('myFile', this.file.slice(this.startOffset, this.file.total), this.file.name);

      // 提交表单数据
      axios.post('http://127.0.0.1:8080/fileUpDown/fileUpload.action', formData, {
        // 取消操作
        cancelToken: this.source.token,
        // 上传进度(与下载进度要互斥)
        onUploadProgress: (event) => {
          this.currentOffset = this.startOffset + event.loaded;
          let progress = Math.floor(this.currentOffset / this.fileSize * 100);
          this.currentPercentage = progress <= 100 ? progress : 100;
        },
      })
      // 上传/下载完成
      .then((result) => {
        // 打印返回结果
        console.log(result);

        // 重置开始偏移量
        this.startOffset = 0;
        // 重置选择的文件
        this.file = null;
        (document.getElementById('myFile') as HTMLFormElement).value = null;
        // 重置选择文件大小
        this.fileSize = 0;
      })
      // 上传/下载失败
      .catch((err) => {
        // 记录已上传进度
        this.startOffset = this.currentOffset;
      })
      // 处理后事
      .then(function() {
        console.log('处理后事');
      });
    }

    // 取消上传
    cancelUploadFile() {
      // 取消请求
      this.source.cancel("取消上传/下载");
      // 记录当前已上传进度
      this.startOffset = this.currentOffset;
    }
  }
</script>

<style lang="less" scoped>
</style>


用户评论