Reputation: 3226
I work on a form where my user upload files to S3. If the user leave the form without validating it, even if files are uploaded, the files upload should be canceled and the files deleted from S3.
I have no trouble deleting the files from my S3 bucket. However, I need to be able to delete them before the user leaves the current route (i.e. page) and skip it if the next route is the same page (i.e. a page refresh).
This is an issue very similar to this one on Github where they say that, basically, it can't be done. Several other similar questions are in SO too, but none offers a satisfying answer.
I wanted to check if it is possible here, since it seems to me that this is a vital feature and I expect that other people may have dealt with it before.
If it can't be done, what workaround would you advise?
Upvotes: 1
Views: 237
Reputation: 3226
I discovered a great trick to detect when the user leave the current page. Here is the recipe:
Attach a subscription (even if empty) to your route controller. This way, route loaded
= subscription active
and route left
= subscription stopped
Add an onStop()
function and put inside it all the server side code you need to execute when the user leave the page. here is how my publication looks (I delete uploaded files when the related form hasn't been submitted when page is left):
Meteor.publish("files", function(sessionId) {
var self = this;
// Here I clean all the files I need to remove because the user has
// not submitted the current form.
self.onStop(function () {
console.log (sessionId + " is cleaning...");
cleanFiles(sessionId)
});
// I look for files related to the current upload session only
if(Users.isInRoles(this.userId, ["user"])) {
return Files.find({"session_id":sessionId, "owner":this.userId}, {});
}
//and I make my publication available in case the if statement failed
return self.ready();
});
Bottom line: as far as I know, it works like a charm. This is a great way to keep track of the user activity and execute code once he leaves the page or a sub-page (whatever template route we attached the subscription to).
Upvotes: 1
Reputation: 4948
That sounds really hard, what if the user exits the browser or their computer loses power? There's NO way to ensure that you could execute code on the client before the browser closed, so you need something on the server.
I don't know your whole process flow, but I imagine you're doing something like uploading a profile pic for a new account & if the account isn't created, then delete it. I'd recommend something like a staging area. They upload the pic & in your database you have the s3 url & a confirmed
flag. The confirm flag defaults to false, and toggles when the form is saved. Then, you run a cron job every hour/day/week on every new picture that was uploaded & delete those that aren't confirmed.
This has the added benefit that if they accidentally close the browser, you are a champ & saved their progress.
Upvotes: 1