我正在使用基于blueimp(http://blueimp.github.com/jQuery-File-Upload)和Ruby on Rails GEM Carrierwave的多文件上传方案。我遇到的问题是用户可以在上传文件之前离开网页。我正在尝试创建一种方法,如果当前正在上载文件并且用户在上载完成之前导航离开页面,那么它应该返回确认对话框。有关如何实现这一点的任何想法?
答案 0 :(得分:1)
这可以通过Javascript的onbeforeunload
事件来完成。
var upload_pending = false;
// ...
// Once upload has started, toggle the boolean flag (in something like
// a click event on the submit button for the form with the file field,
// making sure to toggle it back after the upload finishes
upload_pending = true;
// ...
window.onbeforeunload = function (e) {
e = e || window.event;
if (!upload_pending) return;
// For IE<8 and Firefox prior to version 4
if (e) {
e.returnValue = 'There is a pending upload.';
}
// For Chrome, Safari, IE8+ and Opera 12+
return 'There is a pending upload.';
};
答案 1 :(得分:1)
添加到处理文件上传的表单的末尾。
$(window).bind('beforeunload', function () {
if ($('#fileupload').data('fileupload')._active) {
return 'Leaving now would abort your upload. Are you sure?';
}
});