前端實現文件的斷點續傳

 

2017-08-05 前端大全

(點擊上方公衆號,可快速關注)php

 

做者:imwtrcss

www.cnblogs.com/imwtr/p/5957391.htmlhtml

若有好文章投稿,請點擊 → 這裏瞭解詳情前端

 

早就據說過斷點續傳這種東西,前端也能夠實現一下ajax

斷點續傳在前端的實現主要依賴着HTML5的新特性,因此通常來講在老舊瀏覽器上支持度是不高的json

 

本文經過斷點續傳的簡單例子(前端文件提交+後端PHP文件接收),理解其大體的實現過程後端

 

仍是先以圖片爲例,看看最後的樣子數組

 

 

1、一些知識準備瀏覽器

 

斷點續傳,既然有斷,那就應該有文件分割的過程,一段一段的傳。app

 

之前文件沒法分割,但隨着HTML5新特性的引入,相似普通字符串、數組的分割,咱們能夠可使用slice方法來分割文件。

 

因此斷點續傳的最基本實現也就是:前端經過FileList對象獲取到相應的文件,按照指定的分割方式將大文件分段,而後一段一段地傳給後端,後端再按順序一段段將文件進行拼接。

 

而咱們須要對FileList對象進行修改再提交,在以前的文章中知曉了這種提交的一些注意點,由於FileList對象不能直接更改,因此不能直接經過表單的.submit()方法上傳提交,須要結合FormData對象生成一個新的數據,經過Ajax進行上傳操做。

 

2、實現過程

 

這個例子實現了文件斷點續傳的基本功能,不過手動的「暫停上傳」操做還未實現成功,能夠在上傳過程當中刷新頁面來模擬上傳的中斷,體驗「斷點續傳」、

 

有可能還有其餘一些小bug,但基本邏輯大體如此。

 

1. 前端實現

 

首先選擇文件,列出選中的文件列表信息,而後能夠自定義的作上傳操做

 

(1)因此先設置好頁面DOM結構

 

<!-- 上傳的表單 -->

<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>

<!-- 上傳文件列表中每一個文件的信息模版 -->

 

這裏一併將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;

}

 

(2)接下來是JS的實現解析

 

經過FileList對象咱們能獲取到文件的一些信息

 

 

其中的size就是文件的大小,文件的分分割分片須要依賴這個

 

這裏的size是字節數,因此在界面顯示文件大小時,能夠這樣轉化

 

// 計算文件大小

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';

 

選擇文件後顯示文件的信息,在模版中替換一下數據

 

// 更新文件信息列表

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%時,就直接是從新上傳而不是繼續上傳了)

 

// 初始經過本地記錄,判斷該文件是否曾經上傳過

percent = window.localStorage.getItem(file.name + '_p');

 

if (percent && percent !== '100.0') {

    progress = '已上傳 ' + percent + '%';

    uploadVal = '繼續上傳';

}

 

顯示了文件信息列表

 

 

點擊開始上傳,能夠上傳相應的文件

 

 

上傳文件的時候須要就將文件進行分片分段

 

好比這裏配置的每段1024B,總共chunks段(用來判斷是否爲末段),第chunk段,當前已上傳的百分比percent等

 

須要提一下的是這個暫停上傳的操做,其實我還沒實現出來,暫停不了無奈ing…

 

 

接下來是分段過程

 

// 設置分片的開始結尾

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

 

上傳了一個分段,經過返回的結果判斷是否上傳完畢,是否繼續上傳

 

successfunction (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']);

    }

},

errorfunction () {

    $progress.text(msg['failed']);

}

 

繼續下一分段的上傳時,就進行了遞歸操做,按順序地上傳下一分段

 

截個圖..

 

 

這是完整的JS邏輯,代碼有點兒註釋了應該不難看懂吧哈哈

 

// 所有上傳操做

$(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',

            datafd,

            processDatafalse,

            contentTypefalse,

            timeouttimeout,

            successfunction (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']);

                }

            },

            errorfunction () {

                $progress.text(msg['failed']);

            }

        });

    }

});

 

2. 後端實現

 

這裏的後端實現仍是比較簡單的,主要用依賴了 file_put_contents、file_get_contents 這兩個方法

 

 

要注意一下,經過FormData對象上傳的文件對象,在PHP中也是經過$_FILES全局對象獲取的,還有爲了不上傳後文件中文的亂碼,用一下iconv

 

斷點續傳支持文件的覆蓋,因此若是已經存在完整的文件,就將其刪除

 

// 若是第一次上傳的時候,該文件已經存在,則刪除文件從新上傳

if ($isFirstUpload == '1' && file_exists('upload/'.$fileName) && filesize('upload/'.$fileName) == $totalSize) {

    unlink('upload/'.$fileName);

}

 

使用上述的兩個方法,進行文件信息的追加,別忘了加上 FILE_APPEND 這個參數~

 

// 繼續追加文件數據

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部分

 

<?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

    ));

 

?>

 

先到這兒~

相關文章
相關標籤/搜索