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 和 XML: 使用expat函数(三)
Oct 09 PHP
缓存技术详谈―php
Dec 14 PHP
PHP中的strtr函数使用介绍(str_replace)
Oct 20 PHP
php提示无法加载或mcrypt没有找到 PHP 扩展 mbstring解决办法
Mar 27 PHP
php解析url的三个示例
Jan 20 PHP
php中有关字符串的4个函数substr、strrchr、strstr、ereg介绍和使用例子
Apr 24 PHP
PHP生成各种常见验证码和Ajax验证过程
Jan 10 PHP
使用一个for循环将N*N的二维数组的所有值置1实现方法
May 29 PHP
PHP+原生态ajax实现的省市联动功能详解
Aug 15 PHP
在Laravel中使用DataTables插件的方法
May 29 PHP
php微信开发之图片回复功能
Jun 14 PHP
Laravel框架Eloquent ORM简介、模型建立及查询数据操作详解
Dec 04 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
用Socket发送电子邮件(利用需要验证的SMTP服务器)
2006/10/09 PHP
一个分页的论坛
2006/10/09 PHP
php连接mssql的一些相关经验及注意事项
2013/02/05 PHP
PHP实现图片的等比缩放和Logo水印功能示例
2017/05/04 PHP
php关联数组与索引数组及其显示方法
2018/03/12 PHP
PHP常见字符串操作函数与用法总结
2019/03/04 PHP
一个可以兼容IE FF的加为首页与加入收藏实现代码
2009/11/02 Javascript
jQuery ajax BUG:object doesn't support this property or method
2010/07/06 Javascript
javascript对talbe进行动态添加、删除、验证实现代码
2012/03/29 Javascript
类似天猫商品详情随浏览器移动的示例代码
2014/02/27 Javascript
js图片预加载示例
2014/04/30 Javascript
JavaScript操作URL的相关内容集锦
2015/10/29 Javascript
js倒计时简单实现方法
2015/12/17 Javascript
bootstrap3 兼容IE8浏览器!
2016/05/02 Javascript
快速获取/设置iframe内对象元素的几种js实现方法
2016/05/20 Javascript
jQuery实现区域打印功能代码详解
2016/06/17 Javascript
js获取地址栏中传递的参数(两种方法)
2017/02/08 Javascript
基于node.js的fs核心模块读写文件操作(实例讲解)
2017/09/10 Javascript
JS+HTML实现的圆形可点击区域示例【3种方法】
2018/08/01 Javascript
详解express使用vue-router的history踩坑
2019/06/05 Javascript
Nodejs实现图片上传、压缩预览、定时删除功能
2019/10/25 NodeJs
openlayers 3实现车辆轨迹回放
2020/09/24 Javascript
Python3基础之list列表实例解析
2014/08/13 Python
使用Python脚本在Linux下实现部分Bash Shell的教程
2015/04/17 Python
Python中遍历字典过程中更改元素导致异常的解决方法
2016/05/12 Python
Django中在xadmin中集成DjangoUeditor过程详解
2019/07/24 Python
Selenium环境变量配置(火狐浏览器)及验证实现
2020/12/07 Python
CSS3制作皮卡丘动画壁纸的示例
2020/11/02 HTML / CSS
施华洛世奇德国官网:SWAROVSKI德国
2017/02/01 全球购物
美发店5.1活动方案
2014/01/24 职场文书
大四自我鉴定
2014/02/08 职场文书
素质教育标语
2014/06/27 职场文书
七夕相亲活动策划方案
2014/08/31 职场文书
2014国庆节餐厅促销活动策划方案
2014/09/16 职场文书
神农溪导游词
2015/02/11 职场文书
GPU服务器的多用户配置方法
2022/07/07 Servers