首页 > 解决方案 > 如何取消 vue.js 中文件的上传进度?

问题描述

这是我上传文件的代码,我遇到的问题是我无法取消上传,我该怎么做才能做到这一点?

fileBtn(e, k){
  e.preventDefault();
  const uploader = document.getElementById('uploader');
  let size = 5242880 // equivale a 5MB -> 5242880
  let getFile = e.target.files[0];
  let file_type = getFile.name.split('.').pop();
  let file_name = getFile.name.substr(0, getFile.name.lastIndexOf("."))
  let storageRef = firebase.storage().ref('archivos/' + getFile.name);
  let task = storageRef.put(getFile);
  task.on('state_changed', function progress(snapshot){
    // handle progress
  }, function error(err){
    // handle error
  }, function complete(){
    // handle success
  );
}

I have thought to create a function in the onchange method to render a cancel button to stop de upload transaction, I thought about doing that because when a file is selected to upload, it is automatically uploaded to a database (Firebase). How can I do to avoid this and that when the file is selected, it can be accepted or canceled before the data upload transaction begins?

标签: vue.js

解决方案


storageRef.put returns an UploadTask. This UploadTask has the method cancel, which does what you want. Official docs: https://firebase.google.com/docs/reference/js/firebase.storage.UploadTask#cancel

To access the upload task from another function, you need to store the task in a global variable in fileBtn:

this.task = storageRef.put(getFile); // save it globally in component

Then you need to reset the task in the event handlers (error and complete):

this.task = null

Add a button that calls e.g. cancelBtn and add this function:

cancelBtn() {
    if (this.task) {
        this.task.cancel()
    }
}

推荐阅读