除了axios,还有其他库可以实现上传图片并显示进度吗?

除了axios,还有以下一些库可以实现上传图片并显示进度:

1. Fetch API + XMLHttpRequest(原生方式结合)

虽然Fetch API本身没有直接提供上传进度的监听功能,但可以结合XMLHttpRequest来实现类似效果。

示例代码如下:

<input type="file" id="fileInput" />
<button id="uploadButton">上传图片</button>
<p id="progressText">上传进度:</p>

<script>
  const fileInput = document.getElementById('fileInput');
  const uploadButton = document.getElementById('uploadButton');
  const progressText = document.getElementById('progressText');

  uploadButton.addEventListener('click', () => {
    const file = fileInput.files[0];
    if (file) {
      const formData = new FormData();
      formData.append('image', file);

      const xhr = new XMLHttpRequest();
      xhr.open('POST', '/api/upload');
      xhr.setRequestHeader('Content-Type', 'multipart/form-data');

      xhr.upload.onprogress = function (e) {
        if (e.lengthComputable) {
          const percentComplete = Math.round((e.loaded * 100) / e.total);
          progressText.textContent = `上传进度:${percentComplete}%`;
        }
      };

      xhr.onload = function () {
        if (xhr.status === 200) {
          console.log('图片上传成功');
        } else {
          console.log('图片上传失败');
        }
      };

      xhr.onerror = function () {
        console.log('上传出错');
      };

      xhr.send(formData);
    }
  });
</script>

在上述代码中:

  • 首先获取到文件输入框和上传按钮等DOM元素。
  • 当点击上传按钮时,获取用户选择的文件,创建FormData并添加文件。
  • 然后创建XMLHttpRequest对象,设置请求方法、请求头,通过监听xhr.upload.onprogress事件来获取上传进度并更新到页面上显示的文本元素中。
  • 最后根据xhronloadonerror等事件来处理上传成功、失败等情况。

2. Vue-Resource

Vue-Resource曾经是Vue.js官方推荐的用于处理HTTP请求的库,虽然现在官方不再维护,但依然可以使用它来实现图片上传及显示进度。

安装:

npm install vue-resource

示例用法:

import Vue from 'vue';
import VueResource from 'vue-resource';

Vue.use(VueResource);

new Vue({
  el: 'body',
  data: {
    selectedFile: null,
    uploadProgress: 0
  },
  methods: {
    handleFileUpload(event) {
      this.selectedFile = event.target.files[0];
    },
    submitUpload() {
      const formData = new FormData();
      formData.append('image', this.selectedFile);

      this.$http.post('/api/upload', formData, {
        emulateJSON: false,
        onUploadProgress: progressEvent => {
          if (progressEvent.lengthComputable) {
            const percentComplete = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            this.uploadProgress = percentComplete;
          }
        }
      }).then(response => {
        console.log('图片上传成功', response);
      }).catch(error => {
        console.log('图片上传失败', error);
      });
    }
  }
});

在上述代码中:

  • 首先安装并引入Vue-Resource,并通过Vue.use(VueResource)进行初始化。
  • 在组件的数据部分定义了selectedFileuploadProgress等变量。
  • 通过handleFileUpload方法获取用户选择的文件。
  • submitUpload方法中,创建FormData并添加文件,然后使用this.$http.post发送上传请求,通过设置onUploadProgress属性来监听上传进度并更新uploadProgress变量的值,以便在模板中显示。

3. SuperAgent

SuperAgent是一个功能强大的HTTP客户端库,也可以用于图片上传及显示进度。

安装:

npm install superagent

示例用法:

import superagent from 'superagent';

const app = new Vue({
  el: 'body',
  data: {
    selectedFile: null,
  },
  methods: {
    handleFileUpload(event) {
      this.selectedFile = event.target.files[0];
    },
    submitUpload() {
      const formData = new FormData();
      formData.append('image', this.selectedFile);

      superagent.post('/api/upload')
       .type('form-data')
       .send(formData)
       .on('progress', progressEvent => {
          if (progressEvent.lengthComputable) {
            const percentComplete = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            console.log(`上传进度:${percentComplete}%`);
          }
        })
       .then(response => {
          console.log('图片上传成功', response);
        })
       .catch(error => {
            console.log('图片上传失败', error);
        });
    }
  }
});

在上述代码中:

  • 安装并引入SuperAgent
  • 通过handleFileUpload方法获取用户选择的文件。
  • submitUpload方法中,创建FormData并添加文件,然后使用superagent.post发送上传请求,通过监听on('progress',...)事件来获取上传进度并进行显示(这里只是简单在控制台打印,可根据需要调整为在模板中显示)。

这些库都可以在不同程度上满足上传图片并显示进度的需求,你可以根据项目的具体情况和个人喜好选择合适的库来使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值