• 豌豆资源网
  • 开引网企业服务
  • 服务外包网
  • 什么是断点续传?前端如何实现文件的断点续传

    什么是断点续传?

    就是下载文件时,不必重头开始下载,而是从指定的位置继续下载,这样的功能就叫做断点续传。  断点续传的理解可以分为两部分:一部分是断点,一部分是续传。断点的由来是在下载过程中,将一个下载文件分成了多个部分,同时进行多个部分一起的下载,当某个时间点,任务被暂停了,此时下载暂停的位置就是断点了。续传就是当一个未完成的下载任务再次开始时,会从上次的断点继续传送。

    以前文件无法分割,但随着html5新特性的引入,类似普通字符串、数组的分割,我们可以可以使用slice方法来分割文件。所以断点续传的最基本实现也就是:前端通过FileList对象获取到相应的文件,按照指定的分割方式将大文件分段,然后一段一段地传给后端,后端再按顺序一段段将文件进行拼接。

    而我们需要对FileList对象进行修改再提交,在之前的文章中知晓了这种提交的一些注意点,因为FileList对象不能直接更改,所以不能直接通过表单的.submit()方法上传提交,需要结合FormData对象生成一个新的数据,通过Ajax进行上传操作。

     

    实现过程

    这个例子实现了文件断点续传的基本功能,不过手动的“暂停上传”操作还未实现成功,可以在上传过程中刷新页面来模拟上传的中断,体验“断点续传”、

    有可能还有其他一些小bug,但基本逻辑大致如此。

     

    1. 前端实现

    首先选择文件,列出选中的文件列表信息,然后可以自定义的做上传操作

    1、所以先设置好页面DOM结构

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    <!-- 上传的表单 -->
    <form method="post" id="myForm" action="/fileTest.php" enctype="multipart/form-data">
        <input type="file" id="myFile" multiple>
        <!-- 上传的文件列表 -->
        <table id="upload-list">
            <thead>
                <tr>
                    <th width="35%">文件名</th>
                    <th width="15%">文件类型</th>
                    <th width="15%">文件大小</th>
                    <th width="20%">上传进度</th>
                    <th width="15%">
                        <input type="button" id="upload-all-btn" value="全部上传">
                    </th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </form>
    <!-- 上传文件列表中每个文件的信息模版 -->
    <script type="text/template" id="file-upload-tpl">
        <tr>
            <td>{{fileName}}</td>
              <td>{{fileType}}</td>
              <td>{{fileSize}}</td>
              <td class="upload-progress">{{progress}}</td>
              <td>
                  <input type="button" class="upload-item-btn"  data-name="{{fileName}}" data-size="{{totalSize}}" data-state="default" value="{{uploadVal}}">
              </td>
          </tr>
    </script>

      

    这里一并将css样式扔出来  

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    <style type="text/css">
        body {
            font-family: Arial;
        }
        form {
           margin: 50px auto;
           width: 600px;
        }
        input[type="button"] {
            cursor: pointer;
        }
        table {
           display: none;
            margin-top: 15px;
            border: 1px solid #ddd;
             border-collapse: collapse;
        }
     
        table th {
            color: #666;
        }
        table td,table th {
           padding: 5px;
           border: 1px solid #ddd;
           text-align: center;
           font-size: 14px;
        }
    </style>

      

     

    2.接下来是js的实现解析

    通过FileList对象我们能获取到文件的一些信息 

    其中的size就是文件的大小,文件的分分割分片需要依赖这个,这里的size是字节数,所以在界面显示文件大小时,可以这样转化

    1
    2
    3
    4
    5
    6
    7
    8
    // 计算文件大小
    size = file.size > 1024
      ? file.size / 1024  > 1024
      ? file.size / (1024 * 1024) > 1024
      ? (file.size / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
        : (file.size / (1024 * 1024)).toFixed(2) + 'MB'
        : (file.size / 1024).toFixed(2) + 'KB'
        : (file.size).toFixed(2) + 'B';

      

    选择文件后显示文件的信息,在模版中替换一下数据  

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // 更新文件信息列表
    uploadItem.push(uploadItemTpl
        .replace(/{{fileName}}/g, file.name)
        .replace('{{fileType}}', file.type || file.name.match(/\.\w+$/) + '文件')
            .replace('{{fileSize}}', size)
            .replace('{{progress}}', progress)
            .replace('{{totalSize}}', file.size)
            .replace('{{uploadVal}}', uploadVal)
        );

      

    不过,在显示文件信息的时候,可能这个文件之前之前已经上传过了,为了断点续传,需要判断并在界面上做出提示。通过查询本地看是否有相应的数据(这里的做法是当本地记录的是已经上传100%时,就直接是重新上传而不是继续上传了)

    1
    2
    3
    4
    5
    // 初始通过本地记录,判断该文件是否曾经上传过
     percent = window.localStorage.getItem(file.name + '_p');         if (percent && percent !== '100.0') {
        progress = '已上传 ' + percent + '%';
        uploadVal = '继续上传';
    }

      

    显示了文件信息列表  

    点击开始上传,可以上传相应的文件

    上传文件的时候需要就将文件进行分片分段

    比如这里配置的每段1024B,总共chunks段(用来判断是否为末段),第chunk段,当前已上传的百分比percent等

    需要提一下的是这个暂停上传的操作,其实我还没实现出来,暂停不了无奈ing…

    接下来是分段过程

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // 设置分片的开始结尾
    var blobFrom = chunk * eachSize, // 分段开始
        blobTo = (chunk + 1) * eachSize > totalSize ? totalSize : (chunk + 1) * eachSize, // 分段结尾
        percent = (100 * blobTo / totalSize).toFixed(1), // 已上传的百分比
        timeout = 5000, // 超时时间
        fd = new FormData($('#myForm')[0]);
    fd.append('theFile', findTheFile(fileName).slice(blobFrom, blobTo)); // 分好段的文件
    fd.append('fileName', fileName); // 文件名
    fd.append('totalSize', totalSize); // 文件总大小
    fd.append('isLastChunk', isLastChunk); // 是否为末段
    fd.append('isFirstUpload', times === 'first' ? 1 : 0); // 是否是第一段(第一次上传)
    // 上传之前查询是否以及上传过分片
    chunk = window.localStorage.getItem(fileName + '_chunk') || 0;
    chunk = parseInt(chunk, 10);
    文件应该支持覆盖上传,所以如果文件以及上传完了,现在再上传,应该重置数据以支持覆盖(不然后端就直接追加blob数据了
    // 如果第一次上传就为末分片,即文件已经上传完成,则重新覆盖上传
    if (times === 'first' && isLastChunk === 1) {
        window.localStorage.setItem(fileName + '_chunk', 0);
        chunk = 0;
        isLastChunk = 0;
    }

      

    这个times其实就是个参数,因为要在上一分段传完之后再传下一分段,所以这里的做法是在回调中继续调用这个上传操作

    接下来就是真正的文件上传操作了,用Ajax上传,因为用到了FormData对象,所以不要忘了在$.ajax({}加上这个配置processData: false

    上传了一个分段,通过返回的结果判断是否上传完毕,是否继续上传

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    success: function (rs) {
        rs = jsON.parse(rs);
        // 上传成功
        if (rs.status === 200) {
            // 记录已经上传的百分比
            window.localStorage.setItem(fileName + '_p', percent);
            // 已经上传完毕
            if (chunk === (chunks - 1)) {
                $progress.text(msg['done']);
                $this.val('已经上传').prop('disabled', true).css('cursor', 'not-allowed');
                if (!$('#upload-list').find('.upload-item-btn:not(:disabled)').length) {
                    $('#upload-all-btn').val('已经上传').prop('disabled', true).css('cursor', 'not-allowed');
                }
            } else {
                // 记录已经上传的分片
                window.localStorage.setItem(fileName + '_chunk', ++chunk);
                $progress.text(msg['in'] + percent + '%');
                // 这样设置可以暂停,但点击后动态的设置就暂停不了..
                // if (chunk == 10) {
                //     isPaused = 1;
                // }
                console.log(isPaused);
                if (!isPaused) {
                    startUpload();
                }
            }
        }
        // 上传失败,上传失败分很多种情况,具体按实际来设置
        else if (rs.status === 500) {
            $progress.text(msg['failed']);
        }
    },
    error: function () {
        $progress.text(msg['failed']);
    }

      

    继续下一分段的上传时,就进行了递归操作,按顺序地上传下一分段

    截个图..

    这是完整的js逻辑,代码有点儿注释了应该不难看懂吧哈哈

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    // 全部上传操作
    $(document).on('click', '#upload-all-btn', function () {
        // 未选择文件
        if (!$('#myFile').val()) {
            $('#myFile').focus();
        }
        // 模拟点击其他可上传的文件
        else {
            $('#upload-list .upload-item-btn').each(function () {
                $(this).click();
            });
        }
    });
    // 选择文件-显示文件信息
    $('#myFile').change(function (e) {
        var file,
            uploadItem = [],
            uploadItemTpl = $('#file-upload-tpl').html(),
            size,
            percent,
            progress = '未上传',
            uploadVal = '开始上传';
        for (var i = 0, j = this.files.length; i < j; ++i) {
            file = this.files[i];
            percent = undefined;
            progress = '未上传';
            uploadVal = '开始上传';
            // 计算文件大小
            size = file.size > 1024 ? file.size / 1024 > 1024 ? file.size / (1024 * 1024) > 1024 ? (file.size /
                (1024 * 1024 * 1024)).toFixed(2) + 'GB' : (file.size / (1024 * 1024)).toFixed(2) + 'MB' : (file
                .size / 1024).toFixed(2) + 'KB' : (file.size).toFixed(2) + 'B';
            // 初始通过本地记录,判断该文件是否曾经上传过
            percent = window.localStorage.getItem(file.name + '_p');
            if (percent && percent !== '100.0') {
                progress = '已上传 ' + percent + '%';
                uploadVal = '继续上传';
            }
            // 更新文件信息列表
            uploadItem.push(uploadItemTpl
                .replace(/{{fileName}}/g, file.name)
                .replace('{{fileType}}', file.type || file.name.match(/\.\w+$/) + '文件')
                .replace('{{fileSize}}', size)
                .replace('{{progress}}', progress)
                .replace('{{totalSize}}', file.size)
                .replace('{{uploadVal}}', uploadVal));
        }
        $('#upload-list').children('tbody').html(uploadItem.join(''))
            .end().show();
    });
    /**
    * 上传文件时,提取相应匹配的文件项
    * @param  {String} fileName   需要匹配的文件名
    * @return {FileList}          匹配的文件项目
    */
    function findTheFile(fileName) {
        var files = $('#myFile')[0].files,
            theFile;
        for (var i = 0, j = files.length; i < j; ++i) {
            if (files[i].name === fileName) {
                theFile = files[i];
                break;
            }
        }
        return theFile ? theFile : [];
    }
    // 上传文件
    $(document).on('click', '.upload-item-btn', function () {
        var $this = $(this),
            state = $this.attr('data-state'),
            msg = {
                done: '上传成功',
                failed: '上传失败',
                in : '上传中...',
                paused: '暂停中...'
            },
            fileName = $this.attr('data-name'),
            $progress = $this.closest('tr').find('.upload-progress'),
            eachSize = 1024,
            totalSize = $this.attr('data-size'),
            chunks = Math.ceil(totalSize / eachSize),
            percent,
            chunk,
            // 暂停上传操作
            isPaused = 0;
        // 进行暂停上传操作
        // 未实现,这里通过动态的设置isPaused值并不能阻止下方ajax请求的调用
        if (state === 'uploading') {
            $this.val('继续上传').attr('data-state', 'paused');
            $progress.text(msg['paused'] + percent + '%');
            isPaused = 1;
            console.log('暂停:', isPaused);
        }
        // 进行开始/继续上传操作
        else if (state === 'paused' || state === 'default') {
            $this.val('暂停上传').attr('data-state', 'uploading');
            isPaused = 0;
        }
        // 第一次点击上传
        startUpload('first');
        // 上传操作 times: 第几次
        function startUpload(times) {
            // 上传之前查询是否以及上传过分片
            chunk = window.localStorage.getItem(fileName + '_chunk') || 0;
            chunk = parseInt(chunk, 10);
            // 判断是否为末分片
            var isLastChunk = (chunk == (chunks - 1) ? 1 : 0);
            // 如果第一次上传就为末分片,即文件已经上传完成,则重新覆盖上传
            if (times === 'first' && isLastChunk === 1) {
                window.localStorage.setItem(fileName + '_chunk', 0);
                chunk = 0;
                isLastChunk = 0;
            }
            // 设置分片的开始结尾
            var blobFrom = chunk * eachSize, // 分段开始
                blobTo = (chunk + 1) * eachSize > totalSize ? totalSize : (chunk + 1) * eachSize, // 分段结尾
                percent = (100 * blobTo / totalSize).toFixed(1), // 已上传的百分比
                timeout = 5000, // 超时时间
                fd = new FormData($('#myForm')[0]);
            fd.append('theFile', findTheFile(fileName).slice(blobFrom, blobTo)); // 分好段的文件
            fd.append('fileName', fileName); // 文件名
            fd.append('totalSize', totalSize); // 文件总大小
            fd.append('isLastChunk', isLastChunk); // 是否为末段
            fd.append('isFirstUpload', times === 'first' ? 1 : 0); // 是否是第一段(第一次上传)
            // 上传
            $.ajax({
                type: 'post',
                url: '/fileTest.php',
                data: fd,
                processData: false,
                contentType: false,
                timeout: timeout,
                success: function (rs) {
                    rs = jsON.parse(rs);
                    // 上传成功
                    if (rs.status === 200) {
                        // 记录已经上传的百分比
                        window.localStorage.setItem(fileName + '_p', percent);
                        // 已经上传完毕
                        if (chunk === (chunks - 1)) {
                            $progress.text(msg['done']);
                            $this.val('已经上传').prop('disabled', true).css('cursor', 'not-allowed');
                            if (!$('#upload-list').find('.upload-item-btn:not(:disabled)').length) {
                                $('#upload-all-btn').val('已经上传').prop('disabled', true).css('cursor',
                                    'not-allowed');
                            }
                        } else {
                            // 记录已经上传的分片
                            window.localStorage.setItem(fileName + '_chunk', ++chunk);
                            $progress.text(msg['in'] + percent + '%');
                            // 这样设置可以暂停,但点击后动态的设置就暂停不了..
                            // if (chunk == 10) {
                            //     isPaused = 1;
                            // }
                            console.log(isPaused);
                            if (!isPaused) {
                                startUpload();
                            }
                        }
                    }
                    // 上传失败,上传失败分很多种情况,具体按实际来设置
                    else if (rs.status === 500) {
                        $progress.text(msg['failed']);
                    }
                },
                error: function () {
                    $progress.text(msg['failed']);
                }
            });
        }
    });

      

     

    2. 后端实现

    这里的后端实现还是比较简单的,主要用依赖了 file_put_contents、file_get_contents 这两个方法

    新片场https://www.wode007.com/sites/73286.html 傲视网https://www.wode007.com/sites/73285.html

    要注意一下,通过FormData对象上传的文件对象,在php中也是通过$_FILES全局对象获取的,还有为了避免上传后文件中文的乱码,用一下iconv

    断点续传支持文件的覆盖,所以如果已经存在完整的文件,就将其删除

    // 如果第一次上传的时候,该文件已经存在,则删除文件重新上传
    
    1
    2
    3
    if ($isFirstUpload == '1' && file_exists('upload/'.$fileName) && filesize('upload/'.$fileName) == $totalSize) {
        unlink('upload/'.$fileName);
    }

      

    使用上述的两个方法,进行文件信息的追加,别忘了加上 FILE_APPEND 这个参数~ // 继续追加文件数据
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    if (!file_put_contents('upload/'.$fileName, file_get_contents($_FILES['theFile']['tmp_name']), FILE_APPEND)) {
        $status = 501;
    } else {
        // 在上传的最后片段时,检测文件是否完整(大小是否一致)
        if ($isLastChunk === '1') {
            if (filesize('upload/'.$fileName) == $totalSize) {
                $status = 200;
            } else {
                $status = 502;
            }
        } else {
            $status = 200;
        }
    }

      

     

     

    一般在传完后都需要进行文件的校验吧,所以这里简单校验了文件大小是否一致

    根据实际需求的不同有不同的错误处理方法,这里就先不多处理了

    完整的php部分

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    <?php
        header('Content-type: text/plain; charset=utf-8');
      
        $files = $_FILES['theFile'];
        $fileName = iconv('utf-8', 'gbk', $_REQUEST['fileName']);
        $totalSize = $_REQUEST['totalSize'];
        $isLastChunk = $_REQUEST['isLastChunk'];
        $isFirstUpload = $_REQUEST['isFirstUpload'];
      
        if ($_FILES['theFile']['error'] > 0) {
            $status = 500;
        } else {
            // 此处为一般的文件上传操作
            // if (!move_uploaded_file($_FILES['theFile']['tmp_name'], 'upload/'. $_FILES['theFile']['name'])) {
            //     $status = 501;
            // } else {
            //     $status = 200;
            // }
      
            // 以下部分为文件断点续传操作
            // 如果第一次上传的时候,该文件已经存在,则删除文件重新上传
            if ($isFirstUpload == '1' && file_exists('upload/'. $fileName) && filesize('upload/'. $fileName) == $totalSize) {
                unlink('upload/'. $fileName);
            }
      
            // 否则继续追加文件数据
            if (!file_put_contents('upload/'. $fileName, file_get_contents($_FILES['theFile']['tmp_name']), FILE_APPEND)) {
                $status = 501;
            } else {
                // 在上传的最后片段时,检测文件是否完整(大小是否一致)
                if ($isLastChunk === '1') {
                    if (filesize('upload/'. $fileName) == $totalSize) {
                        $status = 200;
                    } else {
                        $status = 502;
                    }
                } else {
                    $status = 200;
                }
            }
        }
      
        echo json_encode(array(
            'status' => $status,
            'totalSize' => filesize('upload/'. $fileName),
            'isLastChunk' => $isLastChunk
        ));
    ?>

      

     

     
    posted @   前端一点红  阅读(22103)  评论(0编辑  收藏  举报
    (评论功能已被禁用)
    编辑推荐:
    · 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
    · .NET Core 中如何实现缓存的预热?
    · 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
    · AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
    · 基于Microsoft.Extensions.AI核心库实现RAG应用
    阅读排行:
    · 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
    · 地球OL攻略 —— 某应届生求职总结
    · 提示词工程——AI应用必不可少的技术
    · Open-Sora 2.0 重磅开源!
    · 周边上新:园子的第一款马克杯温暖上架
  • 乐游资源网
  • 热爱资源网
  • 灵活用工代发薪平台
  • 企服知识
  • 355软件知识
  • 点击右上角即可分享
    微信分享提示