当文件上载时用户从页面导航时确认

时间:2012-07-10 22:41:53

标签: ruby-on-rails file-upload carrierwave multiple-files

我正在使用基于blueimp(http://blueimp.github.com/jQuery-File-Upload)和Ruby on Rails GEM Carrierwave的多文件上传方案。我遇到的问题是用户可以在上传文件之前离开网页。我正在尝试创建一种方法,如果当前正在上载文件并且用户在上载完成之前导航离开页面,那么它应该返回确认对话框。有关如何实现这一点的任何想法?

2 个答案:

答案 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?';
    }
});