确定最后一个文件块 [英] Determining the last file chunk

查看:96
本文介绍了确定最后一个文件块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过休息为大文件设置文件上传。下面的函数正在处理分块,但我需要能够识别最后一个块,因为我的其余调用更改为 / finishUpload()以提交保存。

I'm trying to setup a file upload through rest for large files. The function below is taking care of chunking but I need to be able to recognize the last chunk because my rest call changes to /finishUpload() in order to commit the save.

现在我只能弄清楚blob何时为空,但我无法弄清楚如何在blob为空之前确定最后一次迭代。

Right now I'm only able to figure out when the blob is empty but I can't figure out how to determine the last iteration before the blob is empty.

这是我在下面用来解析文件的脚本。

This is the script I'm using below to parse my files.

export default function parseFile(file, options) {
  var opts       = typeof options === 'undefined' ? {} : options;
  var fileSize   = file.size;
  var chunkSize  = typeof opts['chunk_size'] === 'undefined' ?  64 * 1024 : parseInt(opts['chunk_size']);
  var binary     = typeof opts['binary'] === 'undefined' ? false : opts['binary'] == true;
  var offset     = 0;
  var self       = this; // we need a reference to the current object
  var readBlock  = null;
  var chunkReadCallback = typeof opts['chunk_read_callback'] === 'function' ? opts['chunk_read_callback'] : function() {};
  var chunkErrorCallback = typeof opts['error_callback'] === 'function' ? opts['error_callback'] : function() {};
  var success = typeof opts['success'] === 'function' ? opts['success'] : function() {};

  var onLoadHandler = function(evt) {
    if (evt.target.result == "") {
      console.log('Chunk empty, call finish');
      success(file);
      return;
    }

    if (evt.target.error == null) {
      chunkReadCallback(evt.target.result, offset).then(function() {
        offset += evt.target.result.length;
        readBlock(offset, chunkSize, file);
      });
    } else {
      chunkErrorCallback(evt.target.error);
      return;
    }
    if (offset >= fileSize) {
      success(file);
      return;
    }
  }

  readBlock = function(_offset, _chunkSize, _file) {
    var r = new FileReader();
    var blob = _file.slice(_offset, _chunkSize + _offset);
    console.log("blob size:", blob.size, "offset:", _offset, "C+S:",_chunkSize + _offset)
    r.onload = onLoadHandler;

    if (binary) {
      r.readAsArrayBuffer(blob);
    } else {
      r.readAsText(blob);
    }
  }
  readBlock(offset, chunkSize, file);
}

Codepen

推荐答案

为什么不依赖文件大小,即检查条件 _chunkSize + _offset> = fileSize

Why not rely on the filesize, i.e. check the condition _chunkSize + _offset >= fileSize?

这篇关于确定最后一个文件块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆