【问题标题】:Confirm When User Navigates Away from Page While File is Uploading文件上传时用户离开页面时确认
【发布时间】:2012-07-10 22:41:53
【问题描述】:

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

【问题讨论】:

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


    【解决方案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.';
    };
    

    【讨论】:

    • 感谢 Deefour,这是非常好的信息,但我想我可能已经找到了一个需要较少工作的解决方案,因为上传文件时 BlueImp 文件上传脚本已经包含活动状态。
    【解决方案2】:

    添加到处理文件上传的表单末尾。

    $(window).bind('beforeunload', function () {
        if ($('#fileupload').data('fileupload')._active) {
            return 'Leaving now would abort your upload. Are you sure?';
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-13
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-06-09
      • 1970-01-01
      • 2011-07-03
      相关资源
      最近更新 更多