Reputation: 11
This is my code to upload a file, the problem that I have is that I can't cancel the uploading, what can I do in order to accomplish that?
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?
Upvotes: 1
Views: 692
Reputation: 5770
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()
}
}
Upvotes: 1