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 相关文章推荐
DISCUZ 分页代码
Jan 02 PHP
php变量范围介绍
Oct 15 PHP
PHP保留两位小数并且四舍五入及不四舍五入的方法
Sep 22 PHP
PHP获取本周第一天和最后一天示例代码
Feb 24 PHP
ThinkPHP3.1新特性之对分组支持的改进与完善概述
Jun 19 PHP
php自动识别文字编码并转换为目标编码的方法
Aug 08 PHP
php版微信公众平台实现预约提交后发送email的方法
Sep 26 PHP
PHP文件上传操作实例详解
Sep 27 PHP
ThinkPHP5实现作业管理系统中处理学生未交作业与已交作业信息的方法
Nov 12 PHP
PHP定义字符串的四种方式详解
Feb 06 PHP
php压缩文件夹最新版
Jul 18 PHP
laravel使用Faker数据填充的实现方法
Apr 12 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
PHP中鲜为人知的10个函数
2014/02/28 PHP
Thinkphp+smarty+uploadify实现无刷新上传
2015/07/30 PHP
ThinkPHP5.0框架控制器继承基类和自定义类示例
2018/05/25 PHP
初学JavaScript第二章
2008/09/30 Javascript
Cookie 注入是怎样产生的
2009/04/08 Javascript
jquery和javascript中如何将一元素的内容赋给另一元素
2014/01/09 Javascript
理解javascript中try...catch...finally
2015/12/25 Javascript
json格式数据的添加,删除及排序方法
2016/01/21 Javascript
js判断登陆用户名及密码是否为空的简单实例
2016/05/16 Javascript
Bootstrap学习笔记之css组件(3)
2016/06/07 Javascript
全面了解JS中的匿名函数
2016/06/29 Javascript
Vue.js学习笔记之修饰符详解
2017/07/25 Javascript
Angularjs中ng-repeat的简单实例
2017/08/25 Javascript
JavaScript new对象的四个过程实例浅析
2018/07/31 Javascript
使用jQuery给Table动态增加行、清空table的方法
2018/09/05 jQuery
vue.js 2.*项目环境搭建、运行、打包发布的详细步骤
2019/05/01 Javascript
使用axios请求时,发送formData请求的示例
2019/10/29 Javascript
[03:28]2014DOTA2国际邀请赛 走近EG战队天才中单Arteezy
2014/07/12 DOTA
查看Python安装路径以及安装包路径小技巧
2015/04/28 Python
Python中利用Scipy包的SIFT方法进行图片识别的实例教程
2016/06/03 Python
win10环境下python3.5安装步骤图文教程
2017/02/03 Python
TensorFlow实现RNN循环神经网络
2018/02/28 Python
Python中多个数组行合并及列合并的方法总结
2018/04/12 Python
python正则表达式之对号入座篇
2018/07/24 Python
Python实现爬取马云的微博功能示例
2019/02/16 Python
如何利用Anaconda配置简单的Python环境
2019/06/24 Python
python+django+selenium搭建简易自动化测试
2020/08/19 Python
Europcar英国:英国汽车和货车租赁
2017/01/21 全球购物
美国社交购物市场:MassGenie
2019/02/18 全球购物
有模特经验的简历自我评价
2013/09/19 职场文书
大学生个人自我鉴定
2013/12/03 职场文书
居委会四风问题个人对照检查材料
2014/09/25 职场文书
2014大学校园光棍节活动策划书
2014/09/29 职场文书
中学后勤工作总结2015
2015/07/22 职场文书
家长会后的感想
2015/08/11 职场文书
Python3 如何开启自带http服务
2021/05/18 Python