使用FileReader进行文件分段读取

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>

<body>
    <!-- 文件上传的框 -->
    <input type="file" name="" id="">
    <!-- 进度条 -->
    <progress max="100" value="0"></progress>
</body>
<script>
    class FileUpLoad {
        constructor(file) {
            this.progress = document.querySelector("progress")
                //实例化一个filereader对象
            this.reader = new FileReader();
            //当前的文件
            this.file = file;
            //分段读取每一段的大小是1M
            this.step = 1024 * 1024;
            // 当前已经读取的位置
            this.loaded = 0;
            // 文件总大小
            this.total = this.file.size;
            //第一次调用
            this.readfile(0);
            // 为FileReader实例绑定事件
            this.readEvent();
        }
        readEvent() {
                // 绑定文件读取中事件
                this.reader.addEventListener("progress", (e) => {
                        // 当前所占的比率
                        this.progress.value = (this.loaded / this.total) * 100

                    })
                    // 绑定文件读取成功事件,每一小段读取完之后都会调用次方法
                this.reader.addEventListener("load", (e) => {
                    console.log(this.reader.result);
                    this.loaded += e.loaded;
                    this.getfile()
                })
            }
            // 读取文件
        readfile(start) {
            let blob
                // 如果slice方法存在那么就分段,相当于切片
            if (this.file.slice) {
                blob = this.file.slice(start, start + this.step)
            } else {
                blob = this.file
            }
            this.reader.readAsText(blob, "utf-8")
        }

        getfile() {
            //如果当前已读取的小于总文件大小那么久继续调用
            if (this.loaded < this.total) {
                this.readfile(this.loaded)
            } else {
                // 读取完成后将进度条置为100%
                this.progress.value = (this.loaded / this.total) * 100
                    // alert("读取成功!")
            }
        }
    }

    const finput = document.querySelector("input")
    finput.addEventListener("change", () => {
        new FileUpLoad(finput.files[0])
    })
</script>

</html>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值