Home  >  Article  >  Backend Development  >  The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)

The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)

高洛峰
高洛峰Original
2016-12-26 14:01:251704browse

I’ve heard about breakpoint resume uploading for a long time, and the front end can also implement it. The implementation of breakpoint resume downloading on the front end mainly relies on the new features of HTML5, so generally speaking, support on older browsers is not high.

This article uses a simple example of breakpoint resumption (front-end file submission + back-end PHP file reception) to understand its general implementation process

Let’s take the picture as an example first and take a look at the final Appearance

The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)

The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)

1. Some knowledge preparations

Resume the download at a broken point. Since there is a break, there should be files The process of segmentation is passed on piece by piece.

In the past, files could not be split, but with the introduction of new features of HTML5, similar to the splitting of ordinary strings and arrays, we can use the slice method to split files.

So the most basic implementation of breakpoint resume transfer is: the front end obtains the corresponding file through the FileList object, divides the large file into segments according to the specified division method, and then passes it to the back end piece by piece. Then splice the files piece by piece in sequence.

We need to modify the FileList object and then submit it. In the previous article, we learned some points to note about this kind of submission. Because the FileList object cannot be changed directly, it cannot be directly passed through the .submit() method of the form. To upload and submit, you need to combine the FormData object to generate a new data and perform the upload operation through Ajax.

2. Implementation process

This example implements the basic function of resuming file upload at breakpoint. However, the manual "pause upload" operation has not yet been successfully implemented. You can refresh the page during the upload process. Simulate the interruption of uploading, experience "breakpoint resume upload",

There may be some other small bugs, but the basic logic is roughly the same.

1. Front-end implementation

First select the file, list the selected file list information, and then customize the upload operation

(1) So set up the page first DOM structure


文件名 文件类型 文件大小 上传进度

Throw out the CSS styles here

(2 ) Next is the implementation analysis of JS

We can get some information about the file through the FileList object

The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)

The size is the size of the file, and the size of the file Splitting and sharding need to rely on this

The size here is the number of bytes, so when the interface displays the file size, it can be converted like this

// 计算文件大小 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';

Show the file information after selecting the file, and replace the data in the template

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

However, when displaying the file information, the file may have been uploaded before After that, in order to resume the download from the breakpoint, you need to make a judgment and provide a prompt on the interface.

Check the local area to see if there is corresponding data (the method here is that when the local record is that 100% has been uploaded, it is directly re-uploaded instead of continuing to upload)

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

Displays the file information list

The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)

Click to start uploading to upload the corresponding file

The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)

When uploading a file, you need to split the file into segments.

For example, each segment configured here is 1024B, the total chunks segment (used to determine whether it is the last segment), the chunk segment, the current uploaded percentage, etc.
What needs to be mentioned is the operation of pausing uploading. In fact, I haven't implemented it yet. I have no choice but to pause it...

The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)

The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)

The next step is the segmentation process

// 设置分片的开始结尾 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 其实就是个参数,因为要在上一分段传完之后再传下一分段,所以这里的做法是在回调中继续调用这个上传操作

The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)

接下来就是真正的文件上传操作了,用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']);
}

   

2. 后端实现

要注意一下,通过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部分

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

   

更多The front-end implements breakpoint resume upload of files (front-end file submission + back-end PHP file reception)相关文章请关注PHP中文网!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn