美文网首页
切片上传_根据文件头判断文件类型_分片合并下载

切片上传_根据文件头判断文件类型_分片合并下载

作者: 时间_7436 | 来源:发表于2022-08-04 15:39 被阅读0次
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>
</head>
<body>
  <input type="file" id="file" onchange="fileChange(this)" />
  <button onclick="download()">download</button>
  <script type="text/javascript">
    let fileData = [];
    let file

  async function fileChange (e) {
    if (e.files.length > 0 && (await valid(e.files[0], "jpg,png,gif"))) {
      file = e.files[0]
      let blobArray = sliceUp(e.files[0], 10 * 1024);
      sendblob(blobArray, 5, e.files[0].size);
    }
  }

  function sliceUp (blob, bytesPerPiece = 5 * 1024 * 1024) {
      let start = 0,
        end = 0,
        index = 0,
        filesize = blob.size,
        blobArray = [];
      //计算文件切片总数
      const totalPieces = Math.ceil(filesize / bytesPerPiece);
      while (index < totalPieces) {
      start = index * bytesPerPiece;
      //++index === totalPieces  最后一片
      end = ++index === totalPieces ? filesize : index * bytesPerPiece;
      const chunk = blob.slice(start, end); //切割文件
      blobArray.push({
        file: chunk,
        name: `${blob.name}(${index})`,
        type: blob.type,
      });
    }
    return blobArray;
  }

  //模拟axios上传
  let _http = (data, ...config) => {
    console.log(data);
   return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(data);
      }, 200);
    });
  };

  function sendblob (blobArray, num, totalSize) {
    // totalSize用来计算总进度 progressObj存储每一片的上传进度
    let progressObj = {};
    //计算进度条
    function computeProgress (key, loaded, total) {
      progressObj[key] = {
        loaded,
        total,
        issuccess: loaded === total,
        key,
      };
      let progress = 0;
      if (progressObj) {
        for (key in progressObj) {
          progress += progressObj[key].loaded;
        }
      }
    if (totalSize > progress && progress > 0) {
      return (progress / totalSize) * 100 + "%";
    }
    return "0%";
  }
  //递归上传,每次五条,成功后继续
  function send (fncarray) {
    return Promise.all(
      fncarray.map((blob) =>
        _http(blob, {
          onUploadProgress: (progressEvent) => {
            computeProgress(
              blob.name,
              progressEvent.loaded,
              progressEvent.total
            );
          },
        })
      )
    ).then((list) => {
      fileData = fileData.concat(list)
      blobArray.splice(0, num);
      if (blobArray.length > 0) {
        send(blobArray.slice(0, num));
      } else {
        console.log('end');
      }
    });
  }
  send(blobArray.slice(0, num));
}

async function valid (file, accept) {
  //根据文件头验证文件类型
  if (!file instanceof Blob) {
    throw Error("仅支持Blob验证");
    // return false
  }
  if (!accept) return;
  const Ext2Hex = {
    jpg: /^(ffd8ffe)[0-4]{1}/,
    png: /^(89504e47){1}/,
    ico: /^(100){1}/,
    gif: /^(47494638){1}/,
  };
  let first4Byte = new DataView(await file.arrayBuffer()).getUint32(
    0,
    false
  );

  const uint32 = Number(first4Byte).toString(16);

  return Object.keys(Ext2Hex).some((key) => {
    if (accept.indexOf(key) > -1) {
      return Ext2Hex[key].test(uint32);
    }
  });
}


function getFile (fileIds, num) {
  let blobs = []
  function getHttpFile (ids) {
    return Promise.all(
      ids.map((name) =>
        _http(name, {
          onUploadProgress: (progressEvent) => { },
        }).then(name => {
          return fileData.find(e => e.name === name)
        })
      )
    ).then(async (list) => {
      blobs = blobs.concat(list)
      fileIds.splice(0, 5);
      if (fileIds.length > 0) {
        await getHttpFile(fileIds.slice(0, 5))
      } else {
        console.log('end');
      }
      return blobs
    });
  }
  return getHttpFile(fileIds.slice(0, 5))
}
//模拟分片下载
function download () {
  // 调接口获取文件信息,根据大小去判断是否分片获取
  // 模拟直接使用上传时赋值的 file
  if (file.size > 10 * 1024) {
    const fileIds = fileData.map(e => e.name);//fileIds 模拟file分割出的文档碎片id/name
    getFile(fileIds, 5).then(blobs => {   //获取文件碎片,每次发5条请求
      const blob = new Blob(blobs.map(e => e.file), {
        type: blobs[0].type
      });
      exprotStart(blob)
    })
  }
}
function exprotStart (blob, name) {
  const link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = name || Date.now();;
  link.click();
  window.URL.revokeObjectURL(link.href);
}
</script>
</body>
</html>

相关文章

网友评论

      本文标题:切片上传_根据文件头判断文件类型_分片合并下载

      本文链接:https://www.haomeiwen.com/subject/bpupwrtx.html