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 相关文章推荐
火车采集器 免费版使出收费版本功能实现原理
Sep 17 PHP
将文件夹压缩成zip文件的php代码
Dec 14 PHP
PHP数据流应用的一个简单实例
Sep 14 PHP
php使用curl发送json格式数据实例
Dec 17 PHP
用PHP代替JS玩转DOM的思路及示例代码
Jun 15 PHP
php判断类是否存在函数class_exists用法分析
Nov 14 PHP
使用PHP生成PDF方法详解
Jan 23 PHP
php+mysqli实现将数据库中一张表信息打印到表格里的方法
Jan 28 PHP
PHP 匿名函数与注意事项详细介绍
Nov 26 PHP
PHP PDOStatement::bindValue讲解
Jan 30 PHP
laravel实现查询最后执行的一条sql语句的方法
Oct 09 PHP
Thinkphp5.0框架使用模型Model的获取器、修改器、软删除数据操作示例
Oct 11 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 MsSql server时遇到的中文编码问题
2009/06/11 PHP
php长字符串定义方法
2012/07/12 PHP
PHP动态规划解决0-1背包问题实例分析
2015/03/23 PHP
PHP数组与对象之间使用递归实现转换的方法
2015/06/24 PHP
php邮件发送的两种方式
2020/04/28 PHP
学习php设计模式 php实现合成模式(composite)
2015/12/08 PHP
PHP7.1实现的AES与RSA加密操作示例
2018/06/15 PHP
php+Ajax处理xml与json格式数据的方法示例
2019/03/04 PHP
修改Laravel自带的认证系统的User类的命名空间的步骤
2019/10/15 PHP
用javascript实现点击链接弹出&quot;图片另存为&quot;而不是直接打开
2007/08/15 Javascript
克隆javascript对象的三个方法小结
2011/01/12 Javascript
js中substring和substr的定义和用法
2014/05/05 Javascript
Webpack+Vue如何导入Jquery和Jquery的第三方插件
2017/02/20 Javascript
js实现文字列表无缝滚动效果
2017/06/23 Javascript
浅谈ECMAScript6新特性之let、const
2017/08/02 Javascript
jQuery实现可兼容IE6的淡入淡出效果告警提示功能示例
2017/09/20 jQuery
JavaScript简单实现合并两个Json对象的方法示例
2017/10/16 Javascript
Vue CLI3搭建的项目中路径相关问题的解决
2018/09/17 Javascript
Vue press 支持图片放大功能的实例代码
2018/11/09 Javascript
Vue如何基于es6导入外部js文件
2020/05/15 Javascript
关于Node.js中频繁修改代码重启服务器的问题
2020/10/15 Javascript
js中实现继承的五种方法
2021/01/25 Javascript
[02:31]《DAC最前线》之选手酒店现场花絮
2015/01/30 DOTA
[01:57]2016完美“圣”典风云人物:国士无双专访
2016/12/04 DOTA
Python自动调用IE打开某个网站的方法
2015/06/03 Python
让python在hadoop上跑起来
2016/01/27 Python
python如何查看系统网络流量的信息
2016/09/12 Python
Python实现模拟登录网易邮箱的方法示例
2018/07/05 Python
python使用matplotlib画柱状图、散点图
2019/03/18 Python
python标准库OS模块详解
2020/03/10 Python
python操作链表的示例代码
2020/09/27 Python
销售辞职报告范文
2014/01/12 职场文书
常务副总经理任命书
2014/06/05 职场文书
作风建设整改方案
2014/10/27 职场文书
毕业论文答辩开场白和结束语
2015/05/27 职场文书
Java无向树分析 实现最小高度树
2022/04/09 Javascript