I have a form which contains a file input within the form and more importantly a cancel button which should cancel a file upload:
var $fileImage = $("<form action='imageupload.php' method='post' class='imageuploadform' ...><label>" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='imagef1_cancel' align='center'><label>" +
"<input type='button' name='cancelImageBtn' class='cancelimage' value='Cancel' /></label>" +
"</p></form>");
Now I have completed everything when it comes to uploading a file into a server and all that. But I have one problem.
The problem I have is that I do not know how to cancel and upload. At the moment if the user clicks on the 'Cancel' button, then nothing happens. What I want to happen is that if the user clicks on the "Cancel" button, then it would navigate to the "stopImageUpload()" function and that it stops the file upload. But how can I do this?
Below is my attempt to create the cancel button function but when the "Cancel" button is clicked, nothing happens.
$(".cancelimage").on("click", function(event) {
console.log("clicked");
event.preventDefault();
stopImageUpload(success);
});
Below is the full code which shows where the cancel button function is placed and the functions which starts the uploading and stops the uploading of the files:
function startImageUpload(imageuploadform){
$(imageuploadform).find('.imagef1_upload_process').css('visibility','visible');
sourceImageForm = imageuploadform;
$(".cancelimage").on("click", function(event) {
console.log("clicked");
event.preventDefault();
stopImageUpload(success);
});
return true;
}
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
$(sourceImageForm).find('.imagef1_upload_process').css('visibility','hidden');
$(sourceImageForm).find('.imagef1_upload_form').css('visibility','visible');
return true;
}
I have a form which contains a file input within the form and more importantly a cancel button which should cancel a file upload:
var $fileImage = $("<form action='imageupload.php' method='post' class='imageuploadform' ...><label>" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='imagef1_cancel' align='center'><label>" +
"<input type='button' name='cancelImageBtn' class='cancelimage' value='Cancel' /></label>" +
"</p></form>");
Now I have completed everything when it comes to uploading a file into a server and all that. But I have one problem.
The problem I have is that I do not know how to cancel and upload. At the moment if the user clicks on the 'Cancel' button, then nothing happens. What I want to happen is that if the user clicks on the "Cancel" button, then it would navigate to the "stopImageUpload()" function and that it stops the file upload. But how can I do this?
Below is my attempt to create the cancel button function but when the "Cancel" button is clicked, nothing happens.
$(".cancelimage").on("click", function(event) {
console.log("clicked");
event.preventDefault();
stopImageUpload(success);
});
Below is the full code which shows where the cancel button function is placed and the functions which starts the uploading and stops the uploading of the files:
function startImageUpload(imageuploadform){
$(imageuploadform).find('.imagef1_upload_process').css('visibility','visible');
sourceImageForm = imageuploadform;
$(".cancelimage").on("click", function(event) {
console.log("clicked");
event.preventDefault();
stopImageUpload(success);
});
return true;
}
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
$(sourceImageForm).find('.imagef1_upload_process').css('visibility','hidden');
$(sourceImageForm).find('.imagef1_upload_form').css('visibility','visible');
return true;
}
Share
Improve this question
asked Apr 14, 2012 at 13:13
user1333290user1333290
1431 gold badge3 silver badges9 bronze badges
2
- possible duplicate of How to stop upload in background? – kirilloid Commented Apr 15, 2012 at 23:01
- @kirilloid no, the link is a dup of this one – ajax333221 Commented Apr 15, 2012 at 23:11
5 Answers
Reset to default 8This an answer for people that may lend here. (not answering completly the question as it is already too old)
I will answer how you can implement cancel upload, or more cancel ajax request. Which can be needed in a lot of applications.
Using axios
You can cancel a request using a cancel token.
The axios cancel token API is based on the withdrawn cancelable promises proposal.
You can create a cancel token using the CancelToken.source factory as shown below:
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
axios.post('/user/12345', {
name: 'new name'
}, {
cancelToken: source.token
})
And to trigger the cancel
// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');
You can also create a cancel token by passing an executor function to the CancelToken constructor:
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel function as a parameter
cancel = c;
})
});
// cancel the request
cancel();
Note: you can cancel several requests with the same cancel token.
doc https://github.com/axios/axios#cancellation
Using XMLHttpRequest:
We use abort() method of the xhr object.
var xhr = new XMLHttpRequest(),
method = "GET",
url = "https://developer.mozilla.org/";
xhr.open(method, url, true);
xhr.send();
if (OH_NOES_WE_NEED_TO_CANCEL_RIGHT_NOW_OR_ELSE) {
xhr.abort();
}
doc https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/abort
There is a possible solution. You can do like that:
$("#cancel").click(function(){
$("#inputfile").remove();
$("#containerof_inputfile").append("<input type=\"file\" id=\"inputfile\"/>");
});
jQuery makes this kind of thing easier. You can call abort on a returned jQuery object. I suppose you can look in the jQuery code to see how it does it if you really want to roll your own.
Edit: I got curious and looked it up. Abort is a method of the XMLHttpRequest function in Javascript.
Once the form has begun submission I don't believe you can stop it without navigating to a new page.
If you make your cancel button redirect to the same page but with a flag in the query string that you can use to show up a cancellation notice that might do the trick.
At least in node, you can use AbortController API to abort script initiated calls.
These calls may also be calls with file upload payloads.
const controller = new AbortController();
const signal = controller.signal;
const fetchSite = async () => {
try {
const response = await fetch('https://google.com/', { signal });
const source = await response.json();
console.log(todo);
} catch (error) {
if (error.name === "AbortError") {
console.log("Operation aborted");
} else {
console.error(err);
}
}
};
fetchSite();
controller.abort();
More info here: https://blog.logrocket.com/complete-guide-abortcontroller-node-js/