Reputation: 1283
I have added the below codes to copying the files in my local machine. In my case, if the user click the cancel button, i would like to stop the file copy progress using c#. My code is below.
JS code:
for(var i = 0; i < file.length; i++){
var formdata = new FormData();
formdata.append("Files", file[i]);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "/Save");
ajax.send(formdata);
}
C# code:
using (FileStream stream = new FileStream(fullPath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (Content)
{
Content.CopyTo(stream);
}
}
I have the cancel button to cancel the file progresss. In that i have aborted the ongoing progress. I have tried the abort() in xml to block the request but it doesn't block the file copying. How can i achieve my requirement.
Upvotes: 0
Views: 789
Reputation: 65
You should have a look on the Async method with the Cancelation token (link)
In save you create a CancellationTokenSource (link) and store it somewhere
Your cancel button then call another endpoint like Cancel (inspired ;) ) that call the Cancel() method on you tokenSource. (CancellationTokenSource has a Token property for your CopyToAsync call)
Regards, Benoit.
ps: you may want to store some unique id along the request if you want to have several users on several files.
EDIT based on @greggz and @Liam comments: You should also move your HTTP endpoint to an async one :)
Upvotes: 1