php结合web uploader插件实现分片上传文件


Posted in PHP onMay 10, 2016

最近研究了下大文件上传的方法,找到了webuploader js 插件进行大文件上传,大家也可以参考这篇文章进行学习:《Web Uploader文件上传插件使用详解》

使用

 使用webuploader分成简单直选要引入

<!--引入CSS-->
<link rel="stylesheet" type="text/css" href="webuploader文件夹/webuploader.css">

<!--引入JS-->
<script type="text/javascript" src="webuploader文件夹/webuploader.js"></script>

HTML部分

<div id="uploader" class="wu-example">
 <!--用来存放文件信息-->
 <div id="thelist" class="uploader-list"></div>
 <div class="btns">
  <div id="picker">选择文件</div>
  <button id="ctlBtn" class="btn btn-default">开始上传   </button>
 </div>
 </div>

初始化Web Uploader

jQuery(function() {
  $list = $('#thelist'),
   $btn = $('#ctlBtn'),
   state = 'pending',
   uploader;

  uploader = WebUploader.create({
   // 不压缩image
   resize: false,
   // swf文件路径
   swf: 'uploader.swf',
   // 文件接收服务端。
   server: upload.php,
   // 选择文件的按钮。可选。
   // 内部根据当前运行是创建,可能是input元素,也可能是flash.
   pick: '#picker',
   chunked: true,
   chunkSize:2*1024*1024,
   auto: true,
   accept: {
    title: 'Images',
    extensions: 'gif,jpg,jpeg,bmp,png',
    mimeTypes: 'image/*'
   }
  });

upload.php处理

以下是根据别人的例子自己拿来改的php 后台代码

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
  header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  header("Cache-Control: no-store, no-cache, must-revalidate");
  header("Cache-Control: post-check=0, pre-check=0", false);
  header("Pragma: no-cache");

  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
   exit; // finish preflight CORS requests here
  }
  if ( !empty($_REQUEST[ 'debug' ]) ) {
   $random = rand(0, intval($_REQUEST[ 'debug' ]) );
   if ( $random === 0 ) {
    header("HTTP/1.0 500 Internal Server Error");
    exit;
   }
  }

  // header("HTTP/1.0 500 Internal Server Error");
  // exit;
  // 5 minutes execution time
  @set_time_limit(5 * 60);
  // Uncomment this one to fake upload time
  // usleep(5000);
  // Settings
  // $targetDir = ini_get("upload_tmp_dir") . DIRECTORY_SEPARATOR . "plupload";
  $targetDir = 'uploads'.DIRECTORY_SEPARATOR.'file_material_tmp';
  $uploadDir = 'uploads'.DIRECTORY_SEPARATOR.'file_material';
  $cleanupTargetDir = true; // Remove old files
  $maxFileAge = 5 * 3600; // Temp file age in seconds
  // Create target dir
  if (!file_exists($targetDir)) {
   @mkdir($targetDir);
  }
  // Create target dir
  if (!file_exists($uploadDir)) {
   @mkdir($uploadDir);
  }
  // Get a file name
  if (isset($_REQUEST["name"])) {
   $fileName = $_REQUEST["name"];
  } elseif (!empty($_FILES)) {
   $fileName = $_FILES["file"]["name"];
  } else {
   $fileName = uniqid("file_");
  }
  $oldName = $fileName;
  $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
  // $uploadPath = $uploadDir . DIRECTORY_SEPARATOR . $fileName;
  // Chunking might be enabled
  $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
  $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
  // Remove old temp files
  if ($cleanupTargetDir) {
   if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
    die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
   }
   while (($file = readdir($dir)) !== false) {
    $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;
    // If temp file is current file proceed to the next
    if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
     continue;
    }
    // Remove temp file if it is older than the max age and is not the current file
    if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
     @unlink($tmpfilePath);
    }
   }
   closedir($dir);
  }

  // Open temp file
  if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
   die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
  }
  if (!empty($_FILES)) {
   if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
    die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
   }
   // Read binary input stream and append it to temp file
   if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
    die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
   }
  } else {
   if (!$in = @fopen("php://input", "rb")) {
    die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
   }
  }
  while ($buff = fread($in, 4096)) {
   fwrite($out, $buff);
  }
  @fclose($out);
  @fclose($in);
  rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
  $index = 0;
  $done = true;
  for( $index = 0; $index < $chunks; $index++ ) {
   if ( !file_exists("{$filePath}_{$index}.part") ) {
    $done = false;
    break;
   }
  }



  if ( $done ) {
   $pathInfo = pathinfo($fileName);
   $hashStr = substr(md5($pathInfo['basename']),8,16);
   $hashName = time() . $hashStr . '.' .$pathInfo['extension'];
   $uploadPath = $uploadDir . DIRECTORY_SEPARATOR .$hashName;

   if (!$out = @fopen($uploadPath, "wb")) {
    die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
   }
   if ( flock($out, LOCK_EX) ) {
    for( $index = 0; $index < $chunks; $index++ ) {
     if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
      break;
     }
     while ($buff = fread($in, 4096)) {
      fwrite($out, $buff);
     }
     @fclose($in);
     @unlink("{$filePath}_{$index}.part");
    }
    flock($out, LOCK_UN);
   }
   @fclose($out);
   $response = [
    'success'=>true,
    'oldName'=>$oldName,
    'filePaht'=>$uploadPath,
    'fileSize'=>$data['size'],
    'fileSuffixes'=>$pathInfo['extension'],
    'file_id'=>$data['id'],
    ];

   die(json_encode($response));
  }

  // Return Success JSON-RPC response
  die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');

更多关于PHP文件上传的精彩内容请关注专题《PHP文件上传操作汇总》,希望对大家有帮助。

以上就是本文的全部内容,希望对大家的学习有所帮助。

PHP 相关文章推荐
很让人受教的 提高php代码质量36计
Sep 05 PHP
php单文件版在线代码编辑器
Mar 12 PHP
PHP使用ODBC连接数据库的方法
Jul 18 PHP
使用纯php代码实现页面伪静态的方法
Jul 25 PHP
PHP YII框架开发小技巧之模型(models)中rules自定义验证规则
Nov 16 PHP
php中preg_replace正则替换用法分析【一次替换多个值】
Jan 17 PHP
PHP实现Unicode编码相互转换的方法示例
Nov 17 PHP
PHP ajax+jQuery 实现批量删除功能实例代码小结
Dec 06 PHP
微信公众平台开发教程⑥ 微信开发集成类的使用图文详解
Apr 10 PHP
php中对象引用和复制实例分析
Aug 14 PHP
PHP Primary script unknown 解决方法总结
Aug 22 PHP
laravel中Redis队列监听中断的分析
Sep 14 PHP
配置Nginx+PHP的正确思路与过程
May 10 #PHP
WordPress中设置Post Type自定义文章类型的实例教程
May 10 #PHP
php+MySQL实现登录时验证登录名和密码是否正确
May 10 #PHP
PHP7+Nginx的配置与安装教程详解
May 10 #PHP
php+mysql实现的二级联动菜单效果详解
May 10 #PHP
浅析Yii2缓存的使用
May 10 #PHP
php简单统计在线人数的方法
May 10 #PHP
You might like
世界收音机发展史
2021/03/01 无线电
php下的权限算法的实现
2007/04/28 PHP
10个实用的PHP正则表达式汇总
2014/10/23 PHP
php实现TCP端口检测的方法
2015/04/01 PHP
PHP下载生成的csv文件及问题总结
2015/08/06 PHP
PHP简单实现无限级分类的方法
2016/05/13 PHP
YII框架行为behaviors用法示例
2019/04/26 PHP
PHPExcel实现的读取多工作表操作示例
2020/04/14 PHP
JQuery 常用方法和事件详细介绍
2013/04/18 Javascript
js展开闭合效果演示代码
2013/07/24 Javascript
简单选项卡 js和jquery制作方法分享
2014/02/26 Javascript
JavaScript通过正则表达式实现表单验证电话号码
2014/03/07 Javascript
JQuery实现当鼠标停留在某区域3秒后自动执行
2014/09/09 Javascript
jQuery遍历DOM节点操作之filter()方法详解
2016/04/14 Javascript
Angular中使用ui router实现系统权限控制及开发遇到问题
2016/09/23 Javascript
Vue.directive自定义指令的使用详解
2017/03/10 Javascript
浅谈使用React.setState需要注意的三点
2017/12/18 Javascript
Es6 Generator函数详细解析
2018/02/24 Javascript
JS实现调用本地摄像头功能示例
2018/05/18 Javascript
如何为你的JavaScript代码日志着色详解
2019/04/08 Javascript
vue项目中使用scss的方法步骤
2019/05/16 Javascript
微信小程序bindtap事件与冒泡阻止详解
2019/08/08 Javascript
vue data恢复初始化数据的实现方法
2019/10/31 Javascript
解决echarts图表使用v-show控制图表显示不全的问题
2020/07/19 Javascript
js定时器出现第一次延迟的原因及解决方法
2021/01/04 Javascript
python处理文本文件实现生成指定格式文件的方法
2014/07/31 Python
python3安装crypto出错及解决方法
2019/07/30 Python
python实现统计代码行数的小工具
2019/09/19 Python
Pytorch中index_select() 函数的实现理解
2019/11/19 Python
浅谈django 重载str 方法
2020/05/19 Python
易程科技软件测试笔试
2013/03/24 面试题
银行贷款收入证明
2014/10/17 职场文书
见义勇为事迹材料
2014/12/24 职场文书
朋友聚会开场白
2015/06/01 职场文书
暖春观后感
2015/06/08 职场文书
SpringBoot2 参数管理实践之入参出参与校验的方式
2021/06/16 Java/Android