php+resumablejs实现的分块上传 断点续传功能示例


Posted in PHP onApril 18, 2017

本文实例讲述了php+resumablejs实现的分块上传 断点续传功能。分享给大家供大家参考,具体如下:

resumablejs官网 http://www.resumablejs.com/

本站下载地址。

upload.html

<!DOCTYPE html>
<html lang="en">
<div>
 <a href="#" rel="external nofollow" id="browseButton" >Select files</a>
<div>
<div>
<input id="btnCancel" type="button" onClick='r.pause()'value="Cancel All Uploads" 
 style="margin-left: 2px; height: 22px; font-size: 8pt;" />
   <br />
</div>
<script src="resumable.js"></script>
<script>
var r = new Resumable({
 target:'upload.php',
 chunkSize:2*1024*1024,
 simultaneousUploads:4,
 testChunks:true,
 throttleProgressCallbacks:1,
});
r.assignBrowse(document.getElementById('browseButton'));
r.on('fileSuccess', function(file){
 // console.debug(file);
 });
r.on('fileProgress', function(file){
 // console.debug(file);
 });
r.on('fileAdded', function(file, event){
 r.upload();
 //console.debug(file, event);
 });
r.on('fileRetry', function(file){
 //console.debug(file);
 });
r.on('fileError', function(file, message){
 //console.debug(file, message);
 });
r.on('uploadStart', function(){
 //console.debug();
 });
r.on('complete', function(){
 //console.debug();
 });
r.on('progress', function(){
 //console.debug();
 });
r.on('error', function(message, file){
 //console.debug(message, file);
 });
r.on('pause', function(file,message){
 //console.debug();
 });
r.on('cancel', function(){
 //console.debug();
 });
</script>
</html>

upload.php

<?php
/**
 * This is the implementation of the server side part of
 * Resumable.js client script, which sends/uploads files
 * to a server in several chunks.
 *
 * The script receives the files in a standard way as if
 * the files were uploaded using standard HTML form (multipart).
 *
 * This PHP script stores all the chunks of a file in a temporary
 * directory (`temp`) with the extension `_part<#ChunkN>`. Once all 
 * the parts have been uploaded, a final destination file is
 * being created from all the stored parts (appending one by one).
 *
 * @author Gregory Chris (http://online-php.com)
 * @email www.online.php@gmail.com
 */
////////////////////////////////////////////////////////////////////
// THE FUNCTIONS
////////////////////////////////////////////////////////////////////
/**
 *
 * Logging operation - to a file (upload_log.txt) and to the stdout
 * @param string $str - the logging string
 */
function _log($str) {
 // log to the output
 $log_str = date('d.m.Y').": {$str}\r\n";
 echo $log_str;
 // log to file
 if (($fp = fopen('upload_log.txt', 'a+')) !== false) {
  fputs($fp, $log_str);
  fclose($fp);
 }
}
/**
 * 
 * Delete a directory RECURSIVELY
 * @param string $dir - directory path
 * @link http://php.net/manual/en/function.rmdir.php
 */
function rrmdir($dir) {
 if (is_dir($dir)) {
  $objects = scandir($dir);
  foreach ($objects as $object) {
   if ($object != "." && $object != "..") {
    if (filetype($dir . "/" . $object) == "dir") {
     rrmdir($dir . "/" . $object); 
    } else {
     unlink($dir . "/" . $object);
    }
   }
  }
  reset($objects);
  rmdir($dir);
 }
}
/**
 *
 * Check if all the parts exist, and 
 * gather all the parts of the file together
 * @param string $dir - the temporary directory holding all the parts of the file
 * @param string $fileName - the original file name
 * @param string $chunkSize - each chunk size (in bytes)
 * @param string $totalSize - original file size (in bytes)
 */
function createFileFromChunks($temp_dir, $fileName, $chunkSize, $totalSize) {
 // count all the parts of this file
 $total_files = 0;
 foreach(scandir($temp_dir) as $file) {
  if (stripos($file, $fileName) !== false) {
   $total_files++;
  }
 }
 // check that all the parts are present
 // the size of the last part is between chunkSize and 2*$chunkSize
 if ($total_files * $chunkSize >= ($totalSize - $chunkSize + 1)) {
  // create the final destination file 
  if (($fp = fopen('temp/'.$fileName, 'w')) !== false) {
   for ($i=1; $i<=$total_files; $i++) {
    fwrite($fp, file_get_contents($temp_dir.'/'.$fileName.'.part'.$i));
    _log('writing chunk '.$i);
   }
   fclose($fp);
  } else {
   _log('cannot create the destination file');
   return false;
  }
  // rename the temporary directory (to avoid access from other 
  // concurrent chunks uploads) and than delete it
  if (rename($temp_dir, $temp_dir.'_UNUSED')) {
   rrmdir($temp_dir.'_UNUSED');
  } else {
   rrmdir($temp_dir);
  }
 }
}
////////////////////////////////////////////////////////////////////
// THE SCRIPT
////////////////////////////////////////////////////////////////////
//check if request is GET and the requested chunk exists or not. this makes testChunks work
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
 $temp_dir = 'temp/'.$_GET['resumableIdentifier'];
 $chunk_file = $temp_dir.'/'.$_GET['resumableFilename'].'.part'.$_GET['resumableChunkNumber'];
 if (file_exists($chunk_file)) {
   header("HTTP/1.0 200 Ok");
  } else
  {
   header("HTTP/1.0 404 Not Found");
  }
 }
// loop through files and move the chunks to a temporarily created directory
if (!empty($_FILES)) foreach ($_FILES as $file) {
 // check the error status
 if ($file['error'] != 0) {
  _log('error '.$file['error'].' in file '.$_POST['resumableFilename']);
  continue;
 }
 // init the destination file (format <filename.ext>.part<#chunk>
 // the file is stored in a temporary directory
 $temp_dir = 'temp/'.$_POST['resumableIdentifier'];
 $dest_file = $temp_dir.'/'.$_POST['resumableFilename'].'.part'.$_POST['resumableChunkNumber'];
 // create the temporary directory
 if (!is_dir($temp_dir)) {
  mkdir($temp_dir, 0777, true);
 }
 // move the temporary file
 if (!move_uploaded_file($file['tmp_name'], $dest_file)) {
  _log('Error saving (move_uploaded_file) chunk '.$_POST['resumableChunkNumber'].' for file '.$_POST['resumableFilename']);
 } else {
  // check if all the parts present, and create the final destination file
  createFileFromChunks($temp_dir, $_POST['resumableFilename'], 
    $_POST['resumableChunkSize'], $_POST['resumableTotalSize']);
 }
}

希望本文所述对大家PHP程序设计有所帮助。

PHP 相关文章推荐
PHP中实现进程间通讯
Oct 09 PHP
加强版phplib的DB类
Mar 31 PHP
PHP 读取文件的正确方法
Apr 29 PHP
PHP Session变量不能传送到下一页的解决方法
Nov 27 PHP
php str_pad() 将字符串填充成指定长度的字符串
Feb 23 PHP
php 学习资料零碎东西
Dec 04 PHP
怎样给PHP源代码加密?PHP二进制加密与解密的解决办法
Apr 22 PHP
关于url地址传参数时字符串有回车造成页面脚本赋值失败的解决方法
Jun 28 PHP
PHP之APC缓存详细介绍 apc模块安装
Jan 13 PHP
php列出mysql表所有行和列的方法
Mar 13 PHP
使用php+swoole对client数据实时更新(一)
Jan 07 PHP
mac下多个php版本快速切换的方法
Oct 09 PHP
ZendFramework2连接数据库操作实例
Apr 18 #PHP
PHP实现的数独求解问题示例
Apr 18 #PHP
PHP使用finfo_file()函数检测上传图片类型的实现方法
Apr 18 #PHP
php实现不通过扩展名准确判断文件类型的方法【finfo_file方法与二进制流】
Apr 18 #PHP
基于thinkPHP3.2实现微信接入及查询token值的方法
Apr 18 #PHP
PHP递归删除多维数组中的某个值
Apr 17 #PHP
Thinkphp5.0自动生成模块及目录的方法详解
Apr 17 #PHP
You might like
PHP中替换换行符的几种方法小结
2012/10/15 PHP
PHP 如何利用phpexcel导入数据库
2013/08/24 PHP
PHP开发框架laravel安装与配置教程
2015/03/13 PHP
wampserver改变默认网站目录的办法
2015/08/05 PHP
PHP针对redis常用操作实例详解
2019/08/17 PHP
js实现页面转发功能示例代码
2013/08/05 Javascript
JQuery ztree带筛选、异步加载实例讲解
2016/02/25 Javascript
如何在Linux上安装Node.js
2016/04/01 Javascript
基于BootStrap Metronic开发框架经验小结【五】Bootstrap File Input文件上传插件的用法详解
2016/05/12 Javascript
全面解析JS字符串和正则表达式中的match、replace、exec等函数
2016/07/01 Javascript
手机端图片缩放旋转全屏查看PhotoSwipe.js插件实现
2016/08/25 Javascript
ionic组件ion-tabs选项卡切换效果实例
2016/08/27 Javascript
通过BootStrap-select插件 js jQuery控制select属性变化
2017/01/03 Javascript
如何理解Vue的.sync修饰符的使用
2017/08/17 Javascript
Node.JS更改Windows注册表Regedit的方法小结
2017/08/18 Javascript
JS+canvas绘制的动态机械表动画效果
2017/09/12 Javascript
基于webpack 实用配置方法总结
2017/09/28 Javascript
NodeJS实现视频转码的示例代码
2017/11/18 NodeJs
vue打包使用Nginx代理解决跨域问题
2018/08/27 Javascript
深入了解JavaScript 私有化
2019/05/30 Javascript
微信小程序动态设置图片大小的方法
2019/11/21 Javascript
微信小程序学习总结(四)事件与冒泡实例分析
2020/06/04 Javascript
JavaScript常用进制转换及位运算实例解析
2020/10/14 Javascript
jquery实现抽奖功能
2020/10/22 jQuery
Pycharm技巧之代码跳转该如何回退
2017/07/16 Python
pyqt 实现为长内容添加滑轮 scrollArea
2019/06/19 Python
numpy求平均值的维度设定的例子
2019/08/24 Python
推荐一些比较有用的css3新属性
2014/11/11 HTML / CSS
梅西酒窖:Macy’s Wine Cellar
2018/01/07 全球购物
奢华时尚的独特视角:La Garçonne
2018/06/07 全球购物
运动会演讲稿100字
2014/08/25 职场文书
教师党的群众路线教育实践活动学习笔记
2014/11/05 职场文书
2014年村党支部工作总结
2014/12/04 职场文书
家长会欢迎词
2015/01/23 职场文书
总结Python连接CS2000的详细步骤
2021/06/23 Python
Java 常见的限流算法详细分析并实现
2022/04/07 Java/Android