欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-21 10:36:52
最近研究了下大文件上传的方法,找到了webuploader js 插件进行大文件上传,大家也可以参考这篇文章进行学习:《web uploader文件上传插件使用详解》 使...

最近研究了下大文件上传的方法,找到了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文件上传操作汇总》,希望对大家有帮助。

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

上一篇:

下一篇: