Javascript: Persist file upload between redirects

百般思念 提交于 2019-12-23 04:05:08

问题


Since there were no answers to this question:

Resumable.js: Persist file uploading between redirects and browser restarts

I am working on a workaround to let users upload their files in a separate popup, while they browse other pages. This is how I am passing my file objects to the popup window:

index.html:

<ol id="chosenFilesList"></ol>
<a href="javascript:void(0);" id="browseButton" style="cursor: pointer;">Select files</a>
<br>
<br>
<br>
<a href="javascript:void(0);" id="uploadButton">Upload</a>

<script src="resumable.js"></script>
<script>

var fileArr = [];

function displaySelectedFiles() {
  var fileList = '';
  for (var i = 0; i < fileArr.length; i++)
    if(fileArr[i])
      fileList += '<li>' + fileArr[i].name + '</li><a style="cursor: pointer;" onclick="removeFile(' + fileArr[i] + ');">Remove</a>';

  //localStorage.setItem('fileArr', fileArr);

  document.getElementById('chosenFilesList').innerHTML = fileList;
}

var r = new Resumable({
  target:'test.html'
});

r.assignBrowse(document.getElementById('browseButton'));

r.on('fileSuccess', function(file){
    console.debug('fileSuccess',file);
  });
r.on('fileProgress', function(file){
    console.debug('fileProgress', file);
  });
r.on('fileAdded', function(file, event){
    //r.upload();
    fileArr.push(file.file);
    displaySelectedFiles();
    console.debug('fileAdded', event);
  });
r.on('filesAdded', function(array){
    //r.upload();
    displaySelectedFiles();
    console.debug('filesAdded', array);
  });
r.on('fileRetry', function(file){
    console.debug(file);
  });
r.on('fileError', function(file, message){
    console.debug('fileError', file, message);
  });
r.on('uploadStart', function(){
    console.debug('uploadStart');
  });
r.on('complete', function(){
    console.debug('complete');
  });
r.on('progress', function(){
    console.debug('progress');
  });
r.on('error', function(message, file){
    console.debug('error', message, file);
  });
r.on('pause', function(){
    console.debug('pause');
  });
r.on('cancel', function(){
    console.debug('cancel');
  });

  var popupWindow;

  var addFiles = function() {
    for (var i = 0; i < fileArr.length; i++) {
      if(fileArr[i])
        popupWindow.r.addFile(fileArr[i]);
    }

    //popupWindow.startUpload();

    window.location.reload();

    setTimeout('popupWindow.focus()', 1);
  };

  document.getElementById('uploadButton').addEventListener('click', function(evt) {
    popupWindow = window.windowPop('', 900, 500);

    if(popupWindow.location.href.indexOf('test.html') === -1) {
      popupWindow.location.href = 'test.html';
      setTimeout(function(){
        popupWindow.onload = addFiles;
        addFiles();
      }, 300);
    } else {
      addFiles();
    }
  });

  function windowPop(url, width, height) {
      var leftPosition, topPosition;
      //Allow for borders.
      leftPosition = (window.screen.width / 2) - ((width / 2) + 10);
      //Allow for title and status bars.
      topPosition = (window.screen.height / 2) - ((height / 2) + 50);
      //Open the window.
      return window.open(url, "Window2", "status=no,height=" + height + ",width=" + width + ",resizable=yes,left=" + leftPosition + ",top=" + topPosition + ",screenX=" + leftPosition + ",screenY=" + topPosition + ",toolbar=no,menubar=no,scrollbars=no,location=no,directories=no");
  }
</script>

test.html:

<!DOCTYPE html>
<html>
  <head>
    <title>Resumable.js - Multiple simultaneous, stable and resumable uploads via the HTML5 File API</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" type="text/css" href="style.css" />
  </head>
  <body>
    <div id="frame">

      <h3>Demo</h3>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
      <script src="resumable.js"></script>

      <div class="resumable-error">
        Your browser, unfortunately, is not supported by Resumable.js. The library requires support for <a href="http://www.w3.org/TR/FileAPI/">the HTML5 File API</a> along with <a href="http://www.w3.org/TR/FileAPI/#normalization-of-params">file slicing</a>.
      </div>

      <div class="resumable-drop" ondragenter="jQuery(this).addClass('resumable-dragover');" ondragend="jQuery(this).removeClass('resumable-dragover');" ondrop="jQuery(this).removeClass('resumable-dragover');">
        Drop video files here to upload or <a class="resumable-browse"><u>select from your computer</u></a>
      </div>

      <div class="resumable-progress">
        <table>
          <tr>
            <td width="100%"><div class="progress-container"><div class="progress-bar"></div></div></td>
            <td class="progress-text" nowrap="nowrap"></td>
            <td class="progress-pause" nowrap="nowrap">
              <a href="#" onclick="r.upload(); return(false);" class="progress-resume-link"><img src="resume.png" title="Resume upload" /></a>
              <a href="#" onclick="r.pause(); return(false);" class="progress-pause-link"><img src="pause.png" title="Pause upload" /></a>
            </td>
          </tr>
        </table>
      </div>

      <ul class="resumable-list"></ul>

      <script>
        var r = new Resumable({
            target:'/java-example/upload',
            chunkSize:1*1024*1024,
            simultaneousUploads:4,
            testChunks: true,
            throttleProgressCallbacks:1,
            method: "octet"
          });
        // Resumable.js isn't supported, fall back on a different method
        if(!r.support) {
          $('.resumable-error').show();
        } else {
          // Show a place for dropping/selecting files
          $('.resumable-drop').show();
          r.assignDrop($('.resumable-drop')[0]);
          r.assignBrowse($('.resumable-browse')[0]);

          // Handle file add event
          r.on('fileAdded', function(file){
              // Show progress pabr
              $('.resumable-progress, .resumable-list').show();
              // Show pause, hide resume
              $('.resumable-progress .progress-resume-link').hide();
              $('.resumable-progress .progress-pause-link').show();
              // Add the file to the list
              $('.resumable-list').append('<li class="resumable-file-'+file.uniqueIdentifier+'">Uploading <span class="resumable-file-name"></span> <span class="resumable-file-progress"></span>');
              $('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-name').html(file.fileName);
              // Actually start the upload
              r.upload();

              console.log(file);
            });
          r.on('pause', function(){
              // Show resume, hide pause
              $('.resumable-progress .progress-resume-link').show();
              $('.resumable-progress .progress-pause-link').hide();
            });
          r.on('complete', function(){
              // Hide pause/resume when the upload has completed
              $('.resumable-progress .progress-resume-link, .resumable-progress .progress-pause-link').hide();
            });
          r.on('fileSuccess', function(file,message){
              // Reflect that the file upload has completed
              $('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html('(completed)');
            });
          r.on('fileError', function(file, message){
              // Reflect that the file upload has resulted in error
              $('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html('(file could not be uploaded: '+message+')');
            });
          r.on('fileProgress', function(file){
              // Handle progress for both the file and the overall upload
              $('.resumable-file-'+file.uniqueIdentifier+' .resumable-file-progress').html(Math.floor(file.progress()*100) + '%');
              $('.progress-bar').css({width:Math.floor(r.progress()*100) + '%'});
            });
        }
      </script>

    </div>
  </body>
</html>

I just added / modified https://github.com/23/resumable.js/tree/master/samples/java sample HTML files. I am just getting all the file objects from file selectors and uploading them in a separate window using resumable.js (I don't think library is important here). It works flawlessly on Chrome and Firefox.

The problem with this approach is, in IE 11- (as far as I tested), the file uploading stops as soon as user is redirected to another page.

Can anybody please tell me how can I make it work in all browsers (hopefully, using pure javascript)?

Also, it will be a lot helpful, if I can just persist an upload between browser restarts as well.

来源:https://stackoverflow.com/questions/34198760/javascript-persist-file-upload-between-redirects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!