
Question:
I have an upload view written in Angularjs. I want to ensure that during an upload if the page is <strong>reloaded</strong> or <strong>closed</strong>; all files that uploaded to the server should be removed for consistency. So what I tried is as following:
// this function is under /upload view, and inside UploadController
window.onunload = function () {
$http.delete(...call delete on my server..);
};
howevever, DELETE does not reach to server, what am I missing?
Answer1:I've had this issue before too. Open up the browser console and go to the network tab. Now navigate away from the page. You will see for a quick moment that your ajax request is marked as (canceled)
because the browser cancels the request as you move away.
<img alt="Save failing" class="b-lazy" data-src="https://i.stack.imgur.com/VM9Zs.png" data-original="https://i.stack.imgur.com/VM9Zs.png" src="https://etrip.eimg.top/images/2019/05/07/timg.gif" />
I've observed this behaviour in google chrome and haven't checked other browsers, but if it doesn't work reliably in one of the most popular browsers then you know this isn't a reliable solution overall.
Basically, there is no reliable way to do this. I've found not even doing the ajax call in window.onbeforeunload
is reliable.
If I were you, I would put an expiry date on your uploaded files and have a cron job that deletes them after the expiry date is reached. Even if window.onunload
worked, it still wouldn't be a reliable solution—for example, when a user's machine unexpectedly shuts down.