欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

前端實(shí)現(xiàn)文件的斷點(diǎn)續(xù)傳(前端文件提交+后端PHP文件接收)

 更新時(shí)間:2016年11月04日 10:30:25   投稿:mrr  
本文通過(guò)斷點(diǎn)續(xù)傳的簡(jiǎn)單例子(前端文件提交+后端PHP文件接收),本文以圖片為實(shí)例給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,感興趣的朋友一起看看吧

早就聽說(shuō)過(guò)斷點(diǎn)續(xù)傳這種東西,前端也可以實(shí)現(xiàn)一下。斷點(diǎn)續(xù)傳在前端的實(shí)現(xiàn)主要依賴著HTML5的新特性,所以一般來(lái)說(shuō)在老舊瀏覽器上支持度是不高的。

本文通過(guò)斷點(diǎn)續(xù)傳的簡(jiǎn)單例子(前端文件提交+后端PHP文件接收),理解其大致的實(shí)現(xiàn)過(guò)程

還是先以圖片為例,看看最后的樣子

一、一些知識(shí)準(zhǔn)備

斷點(diǎn)續(xù)傳,既然有斷,那就應(yīng)該有文件分割的過(guò)程,一段一段的傳。

以前文件無(wú)法分割,但隨著HTML5新特性的引入,類似普通字符串、數(shù)組的分割,我們可以可以使用slice方法來(lái)分割文件。

所以斷點(diǎn)續(xù)傳的最基本實(shí)現(xiàn)也就是:前端通過(guò)FileList對(duì)象獲取到相應(yīng)的文件,按照指定的分割方式將大文件分段,然后一段一段地傳給后端,后端再按順序一段段將文件進(jìn)行拼接。

而我們需要對(duì)FileList對(duì)象進(jìn)行修改再提交,在 之前的文章 中知曉了這種提交的一些注意點(diǎn),因?yàn)镕ileList對(duì)象不能直接更改,所以不能直接通過(guò)表單的.submit()方法上傳提交,需要結(jié)合FormData對(duì)象生成一個(gè)新的數(shù)據(jù),通過(guò)Ajax進(jìn)行上傳操作。

二、實(shí)現(xiàn)過(guò)程

這個(gè)例子實(shí)現(xiàn)了文件斷點(diǎn)續(xù)傳的基本功能,不過(guò)手動(dòng)的“暫停上傳”操作還未實(shí)現(xiàn)成功,可以在上傳過(guò)程中刷新頁(yè)面來(lái)模擬上傳的中斷,體驗(yàn)“斷點(diǎn)續(xù)傳”、

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

1. 前端實(shí)現(xiàn)

首先選擇文件,列出選中的文件列表信息,然后可以自定義的做上傳操作

(1)所以先設(shè)置好頁(yè)面DOM結(jié)構(gòu)

<!-- 上傳的表單 -->
<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%">上傳進(jìn)度</th>
<th width="15%">
<input type="button" id="upload-all-btn" value="全部上傳">
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<!-- 上傳文件列表中每個(gè)文件的信息模版 -->
<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樣式扔出來(lái)

<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)接下來(lái)是JS的實(shí)現(xiàn)解析

通過(guò)FileList對(duì)象我們能獲取到文件的一些信息

 

其中的size就是文件的大小,文件的分分割分片需要依賴這個(gè)

這里的size是字節(jié)數(shù),所以在界面顯示文件大小時(shí),可以這樣轉(zhuǎn)化

// 計(jì)算文件大小 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';

選擇文件后顯示文件的信息,在模版中替換一下數(shù)據(jù)

// 更新文件信息列表 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)
);

不過(guò),在顯示文件信息的時(shí)候,可能這個(gè)文件之前之前已經(jīng)上傳過(guò)了,為了斷點(diǎn)續(xù)傳,需要判斷并在界面上做出提示。

通過(guò)查詢本地看是否有相應(yīng)的數(shù)據(jù)(這里的做法是當(dāng)本地記錄的是已經(jīng)上傳100%時(shí),就直接是重新上傳而不是繼續(xù)上傳了)

// 初始通過(guò)本地記錄,判斷該文件是否曾經(jīng)上傳過(guò) percent = window.localStorage.getItem(file.name + '_p'); if (percent && percent !== '100.0') {
progress = '已上傳 ' + percent + '%';
uploadVal = '繼續(xù)上傳';
}

顯示了文件信息列表

 

點(diǎn)擊開始上傳,可以上傳相應(yīng)的文件

 

上傳文件的時(shí)候需要就將文件進(jìn)行分片分段。

比如這里配置的每段1024B,總共chunks段(用來(lái)判斷是否為末段),第chunk段,當(dāng)前已上傳的百分比percent等。
需要提一下的是這個(gè)暫停上傳的操作,其實(shí)我還沒實(shí)現(xiàn)出來(lái),暫停不了無(wú)奈ing...

接下來(lái)是分段過(guò)程

// 設(shè)置分片的開始結(jié)尾 var blobFrom = chunk * eachSize, // 分段開始 blobTo = (chunk + 1) * eachSize > totalSize ? totalSize : (chunk + 1) * eachSize, // 分段結(jié)尾 percent = (100 * blobTo / totalSize).toFixed(1), // 已上傳的百分比 timeout = 5000, // 超時(shí)時(shí)間 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); // 是否是第一段(第一次上傳)
// 上傳之前查詢是否以及上傳過(guò)分片 chunk = window.localStorage.getItem(fileName + '_chunk') || 0;
chunk = parseInt(chunk, 10);

文件應(yīng)該支持覆蓋上傳,所以如果文件以及上傳完了,現(xiàn)在再上傳,應(yīng)該重置數(shù)據(jù)以支持覆蓋(不然后端就直接追加 blob數(shù)據(jù)了)

// 如果第一次上傳就為末分片,即文件已經(jīng)上傳完成,則重新覆蓋上傳 if (times === 'first' && isLastChunk === 1) { window.localStorage.setItem(fileName + '_chunk', 0);
chunk = 0;
isLastChunk = 0;
}

這個(gè) times 其實(shí)就是個(gè)參數(shù),因?yàn)橐谏弦环侄蝹魍曛笤賯飨乱环侄?,所以這里的做法是在回調(diào)中繼續(xù)調(diào)用這個(gè)上傳操作

 

接下來(lái)就是真正的文件上傳操作了,用Ajax上傳,因?yàn)橛玫搅薋ormData對(duì)象,所以不要忘了在$.ajax({}加上這個(gè)配置processData: false

上傳了一個(gè)分段,通過(guò)返回的結(jié)果判斷是否上傳完畢,是否繼續(xù)上傳

success: function(rs) {
rs = JSON.parse(rs); // 上傳成功 if (rs.status === 200) { // 記錄已經(jīng)上傳的百分比 window.localStorage.setItem(fileName + '_p', percent); // 已經(jīng)上傳完畢 if (chunk === (chunks - 1)) {
$progress.text(msg['done']);
$this.val('已經(jīng)上傳').prop('disabled', true).css('cursor', 'not-allowed'); if (!$('#upload-list').find('.upload-item-btn:not(:disabled)').length) {
$('#upload-all-btn').val('已經(jīng)上傳').prop('disabled', true).css('cursor', 'not-allowed');
}
} else { // 記錄已經(jīng)上傳的分片 window.localStorage.setItem(fileName + '_chunk', ++chunk);
$progress.text(msg['in'] + percent + '%'); // 這樣設(shè)置可以暫停,但點(diǎn)擊后動(dòng)態(tài)的設(shè)置就暫停不了.. // if (chunk == 10) { // isPaused = 1; // } console.log(isPaused); 
if (!isPaused) {
startUpload();
}
}
} 
// 上傳失敗,上傳失敗分很多種情況,具體按實(shí)際來(lái)設(shè)置 else if (rs.status === 500) {
$progress.text(msg['failed']);
}
},
error: function() {
$progress.text(msg['failed']);
}

繼續(xù)下一分段的上傳時(shí),就進(jìn)行了遞歸操作,按順序地上傳下一分段

截個(gè)圖..

 

這是完整的JS邏輯,代碼有點(diǎn)兒注釋了應(yīng)該不難看懂吧哈哈

2. 后端實(shí)現(xiàn)

這里的后端實(shí)現(xiàn)還是比較簡(jiǎn)單的,主要用依賴了 file_put_contents、file_get_contents 這兩個(gè)方法

 

要注意一下,通過(guò)FormData對(duì)象上傳的文件對(duì)象,在PHP中也是通過(guò)$_FILES全局對(duì)象獲取的,還有為了避免上傳后文件中文的亂碼,用一下iconv
斷點(diǎn)續(xù)傳支持文件的覆蓋,所以如果已經(jīng)存在完整的文件,就將其刪除

// 如果第一次上傳的時(shí)候,該文件已經(jīng)存在,則刪除文件重新上傳 if ($isFirstUpload == '1' && file_exists('upload/'. $fileName) && filesize('upload/'. $fileName) == $totalSize) {
unlink('upload/'. $fileName);
}

使用上述的兩個(gè)方法,進(jìn)行文件信息的追加,別忘了加上 FILE_APPEND 這個(gè)參數(shù)~

// 繼續(xù)追加文件數(shù)據(jù) if (!file_put_contents('upload/'. $fileName, file_get_contents($_FILES['theFile']['tmp_name']), FILE_APPEND)) {
$status = 501;
} else { // 在上傳的最后片段時(shí),檢測(cè)文件是否完整(大小是否一致) if ($isLastChunk === '1') { if (filesize('upload/'. $fileName) == $totalSize) {
$status = 200;
} else {
$status = 502;
}
} else {
$status = 200;
}
}

一般在傳完后都需要進(jìn)行文件的校驗(yàn)吧,所以這里簡(jiǎn)單校驗(yàn)了文件大小是否一致。

根據(jù)實(shí)際需求的不同有不同的錯(cuò)誤處理方法,這里就先不多處理了

完整的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; // } // 以下部分為文件斷點(diǎn)續(xù)傳操作 // 如果第一次上傳的時(shí)候,該文件已經(jīng)存在,則刪除文件重新上傳 if ($isFirstUpload == '1' && file_exists('upload/'. $fileName) && filesize('upload/'. $fileName) == $totalSize) {
unlink('upload/'. $fileName);
} // 否則繼續(xù)追加文件數(shù)據(jù) if (!file_put_contents('upload/'. $fileName, file_get_contents($_FILES['theFile']['tmp_name']), FILE_APPEND)) {
$status = 501;
} else { // 在上傳的最后片段時(shí),檢測(cè)文件是否完整(大小是否一致) 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
)); ?>

相關(guān)文章

最新評(píng)論