文件分片

62 阅读1分钟
/**
 * 文件分片
 *
 * @param {*} file        文件对象
 * @param {*} chunkSize   分片大小
 * @param {*} progress    分片进度
 */
export function slice(file, chunkSize, progress) {
  let blobSlice =
    File.prototype.slice ||
    File.prototype.mozSlice ||
    File.prototype.webkitSlice;

  let totalChunk = Math.ceil(file.size / chunkSize);
  let currentChunk = 0;
  let fileReader = new FileReader();
  let chunks = [];

  // 当有数据载入时
  fileReader.onload = (e) => {
    chunks.push(e.target.result);
    currentChunk++;

    if (progress) {
      let progressValue = currentChunk / totalChunk;
      let progressPercentValue = parseFloat((progressValue * 100).toFixed(2));
      progress(progressPercentValue);
    }

    if (currentChunk < totalChunk) {
      loadNext();
    } else {
      return Promise.resolve(chunks);
    }
  };

  // 当发生错误时
  fileReader.onerror = () => {
    return Promise.reject();
  };

  function loadNext() {
    let beginIndex = currentChunk * chunkSize;
    let endIndex = beginIndex + chunkSize;
    if (endIndex >= file.size) {
      endIndex = file.size;
    }

    fileReader.readAsArrayBuffer(blobSlice.call(file, beginIndex, endIndex));
  }

  loadNext();
}