早就聽說過斷點續傳這種東西,前端也可以實現一下
斷點續傳在前端的實現主要依賴着HTML5的新特性,所以一般來說在老舊瀏覽器上支持度是不高的
本文通過斷點續傳的簡單例子(前端文件提交+后端PHP文件接收),理解其大致的實現過程
還是先以圖片為例,看看最后的樣子

一、一些知識准備
斷點續傳,既然有斷,那就應該有文件分割的過程,一段一段的傳。
以前文件無法分割,但隨着HTML5新特性的引入,類似普通字符串、數組的分割,我們可以可以使用slice方法來分割文件。
所以斷點續傳的最基本實現也就是:前端通過FileList對象獲取到相應的文件,按照指定的分割方式將大文件分段,然后一段一段地傳給后端,后端再按順序一段段將文件進行拼接。
而我們需要對FileList對象進行修改再提交,在之前的文章中知曉了這種提交的一些注意點,因為FileList對象不能直接更改,所以不能直接通過表單的.submit()方法上傳提交,需要結合FormData對象生成一個新的數據,通過Ajax進行上傳操作。
二、實現過程
這個例子實現了文件斷點續傳的基本功能,不過手動的“暫停上傳”操作還未實現成功,可以在上傳過程中刷新頁面來模擬上傳的中斷,體驗“斷點續傳”、
有可能還有其他一些小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> <!-- 上傳文件列表中每個文件的信息模版 --> <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樣式扔出來
<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是字節數,所以在界面顯示文件大小時,可以這樣轉化
// 計算文件大小 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
上傳了一個分段,通過返回的結果判斷是否上傳完畢,是否繼續上傳
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 <script type="text/javascript" src="jquery.js"></script> 2 <script type="text/javascript"> 3 // 全部上傳操作 4 $(document).on('click', '#upload-all-btn', function() { 5 // 未選擇文件 6 if (!$('#myFile').val()) { 7 $('#myFile').focus(); 8 } 9 // 模擬點擊其他可上傳的文件 10 else { 11 $('#upload-list .upload-item-btn').each(function() { 12 $(this).click(); 13 }); 14 } 15 }); 16 17 // 選擇文件-顯示文件信息 18 $('#myFile').change(function(e) { 19 var file, 20 uploadItem = [], 21 uploadItemTpl = $('#file-upload-tpl').html(), 22 size, 23 percent, 24 progress = '未上傳', 25 uploadVal = '開始上傳'; 26 27 for (var i = 0, j = this.files.length; i < j; ++i) { 28 file = this.files[i]; 29 30 percent = undefined; 31 progress = '未上傳'; 32 uploadVal = '開始上傳'; 33 34 // 計算文件大小 35 size = file.size > 1024 36 ? file.size / 1024 > 1024 37 ? file.size / (1024 * 1024) > 1024 38 ? (file.size / (1024 * 1024 * 1024)).toFixed(2) + 'GB' 39 : (file.size / (1024 * 1024)).toFixed(2) + 'MB' 40 : (file.size / 1024).toFixed(2) + 'KB' 41 : (file.size).toFixed(2) + 'B'; 42 43 // 初始通過本地記錄,判斷該文件是否曾經上傳過 44 percent = window.localStorage.getItem(file.name + '_p'); 45 46 if (percent && percent !== '100.0') { 47 progress = '已上傳 ' + percent + '%'; 48 uploadVal = '繼續上傳'; 49 } 50 51 // 更新文件信息列表 52 uploadItem.push(uploadItemTpl 53 .replace(/{{fileName}}/g, file.name) 54 .replace('{{fileType}}', file.type || file.name.match(/\.\w+$/) + '文件') 55 .replace('{{fileSize}}', size) 56 .replace('{{progress}}', progress) 57 .replace('{{totalSize}}', file.size) 58 .replace('{{uploadVal}}', uploadVal) 59 ); 60 } 61 62 $('#upload-list').children('tbody').html(uploadItem.join('')) 63 .end().show(); 64 }); 65 66 /** 67 * 上傳文件時,提取相應匹配的文件項 68 * @param {String} fileName 需要匹配的文件名 69 * @return {FileList} 匹配的文件項目 70 */ 71 function findTheFile(fileName) { 72 var files = $('#myFile')[0].files, 73 theFile; 74 75 for (var i = 0, j = files.length; i < j; ++i) { 76 if (files[i].name === fileName) { 77 theFile = files[i]; 78 break; 79 } 80 } 81 82 return theFile ? theFile : []; 83 } 84 85 // 上傳文件 86 $(document).on('click', '.upload-item-btn', function() { 87 var $this = $(this), 88 state = $this.attr('data-state'), 89 msg = { 90 done: '上傳成功', 91 failed: '上傳失敗', 92 in: '上傳中...', 93 paused: '暫停中...' 94 }, 95 fileName = $this.attr('data-name'), 96 $progress = $this.closest('tr').find('.upload-progress'), 97 eachSize = 1024, 98 totalSize = $this.attr('data-size'), 99 chunks = Math.ceil(totalSize / eachSize), 100 percent, 101 chunk, 102 // 暫停上傳操作 103 isPaused = 0; 104 105 // 進行暫停上傳操作 106 // 未實現,這里通過動態的設置isPaused值並不能阻止下方ajax請求的調用 107 if (state === 'uploading') { 108 $this.val('繼續上傳').attr('data-state', 'paused'); 109 $progress.text(msg['paused'] + percent + '%'); 110 isPaused = 1; 111 console.log('暫停:', isPaused); 112 } 113 // 進行開始/繼續上傳操作 114 else if (state === 'paused' || state === 'default') { 115 $this.val('暫停上傳').attr('data-state', 'uploading'); 116 isPaused = 0; 117 } 118 119 // 第一次點擊上傳 120 startUpload('first'); 121 122 // 上傳操作 times: 第幾次 123 function startUpload(times) { 124 // 上傳之前查詢是否以及上傳過分片 125 chunk = window.localStorage.getItem(fileName + '_chunk') || 0; 126 chunk = parseInt(chunk, 10); 127 // 判斷是否為末分片 128 var isLastChunk = (chunk == (chunks - 1) ? 1 : 0); 129 130 // 如果第一次上傳就為末分片,即文件已經上傳完成,則重新覆蓋上傳 131 if (times === 'first' && isLastChunk === 1) { 132 window.localStorage.setItem(fileName + '_chunk', 0); 133 chunk = 0; 134 isLastChunk = 0; 135 } 136 137 // 設置分片的開始結尾 138 var blobFrom = chunk * eachSize, // 分段開始 139 blobTo = (chunk + 1) * eachSize > totalSize ? totalSize : (chunk + 1) * eachSize, // 分段結尾 140 percent = (100 * blobTo / totalSize).toFixed(1), // 已上傳的百分比 141 timeout = 5000, // 超時時間 142 fd = new FormData($('#myForm')[0]); 143 144 fd.append('theFile', findTheFile(fileName).slice(blobFrom, blobTo)); // 分好段的文件 145 fd.append('fileName', fileName); // 文件名 146 fd.append('totalSize', totalSize); // 文件總大小 147 fd.append('isLastChunk', isLastChunk); // 是否為末段 148 fd.append('isFirstUpload', times === 'first' ? 1 : 0); // 是否是第一段(第一次上傳) 149 150 // 上傳 151 $.ajax({ 152 type: 'post', 153 url: '/fileTest.php', 154 data: fd, 155 processData: false, 156 contentType: false, 157 timeout: timeout, 158 success: function(rs) { 159 rs = JSON.parse(rs); 160 161 // 上傳成功 162 if (rs.status === 200) { 163 // 記錄已經上傳的百分比 164 window.localStorage.setItem(fileName + '_p', percent); 165 166 // 已經上傳完畢 167 if (chunk === (chunks - 1)) { 168 $progress.text(msg['done']); 169 $this.val('已經上傳').prop('disabled', true).css('cursor', 'not-allowed'); 170 if (!$('#upload-list').find('.upload-item-btn:not(:disabled)').length) { 171 $('#upload-all-btn').val('已經上傳').prop('disabled', true).css('cursor', 'not-allowed'); 172 } 173 } else { 174 // 記錄已經上傳的分片 175 window.localStorage.setItem(fileName + '_chunk', ++chunk); 176 177 $progress.text(msg['in'] + percent + '%'); 178 // 這樣設置可以暫停,但點擊后動態的設置就暫停不了.. 179 // if (chunk == 10) { 180 // isPaused = 1; 181 // } 182 console.log(isPaused); 183 if (!isPaused) { 184 startUpload(); 185 } 186 187 } 188 } 189 // 上傳失敗,上傳失敗分很多種情況,具體按實際來設置 190 else if (rs.status === 500) { 191 $progress.text(msg['failed']); 192 } 193 }, 194 error: function() { 195 $progress.text(msg['failed']); 196 } 197 }); 198 } 199 }); 200 201 </script>
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部分
1 <?php 2 header('Content-type: text/plain; charset=utf-8'); 3 4 $files = $_FILES['theFile']; 5 $fileName = iconv('utf-8', 'gbk', $_REQUEST['fileName']); 6 $totalSize = $_REQUEST['totalSize']; 7 $isLastChunk = $_REQUEST['isLastChunk']; 8 $isFirstUpload = $_REQUEST['isFirstUpload']; 9 10 if ($_FILES['theFile']['error'] > 0) { 11 $status = 500; 12 } else { 13 // 此處為一般的文件上傳操作 14 // if (!move_uploaded_file($_FILES['theFile']['tmp_name'], 'upload/'. $_FILES['theFile']['name'])) { 15 // $status = 501; 16 // } else { 17 // $status = 200; 18 // } 19 20 // 以下部分為文件斷點續傳操作 21 // 如果第一次上傳的時候,該文件已經存在,則刪除文件重新上傳 22 if ($isFirstUpload == '1' && file_exists('upload/'. $fileName) && filesize('upload/'. $fileName) == $totalSize) { 23 unlink('upload/'. $fileName); 24 } 25 26 // 否則繼續追加文件數據 27 if (!file_put_contents('upload/'. $fileName, file_get_contents($_FILES['theFile']['tmp_name']), FILE_APPEND)) { 28 $status = 501; 29 } else { 30 // 在上傳的最后片段時,檢測文件是否完整(大小是否一致) 31 if ($isLastChunk === '1') { 32 if (filesize('upload/'. $fileName) == $totalSize) { 33 $status = 200; 34 } else { 35 $status = 502; 36 } 37 } else { 38 $status = 200; 39 } 40 } 41 } 42 43 echo json_encode(array( 44 'status' => $status, 45 'totalSize' => filesize('upload/'. $fileName), 46 'isLastChunk' => $isLastChunk 47 )); 48 49 ?>
先到這兒~
