大文件webuploader的基本使用

需要先去下载webuploader包

http://fex.baidu.com/webuploader/download.html

webuploader的简单使用

需要准备 

webuploader.js  uploader.swf  jQuery

html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="webuploader.js"></script>
    <style type="text/css">
      .webuploader-container {
            position: relative;
        }
        .webuploader-element-invisible {
            position: absolute !important;
            clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
            clip: rect(1px,1px,1px,1px);
        }
        .webuploader-pick {
            position: relative;
            display: inline-block;
            cursor: pointer;
            background: #00b7ee;
            padding: 10px 15px;
            color: #fff;
            text-align: center;
            border-radius: 3px;
            overflow: hidden;
        }
        .webuploader-pick-hover {
            background: #00a2d4;
        }
 
        .webuploader-pick-disable {
            opacity: 0.6;
            pointer-events:none;
        }
    </style>
</head>
<body>
    <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>
     <div id="fileList"></div>
     <div id="ss"></div>
</body>
</html>

script代码

<script type="text/javascript">
    jQuery(function() {
        var  uploader;
        uploader = WebUploader.create({
               resize: false, // 不压缩image     
               swf: 'uploader.swf',// swf文件路径    
               server: 'upload.php', // 文件接收服务端。 
               pick: '#picker',// 选择文件的按钮。可选。内部根据当前运行是创建,可能是input元素,也可能是flash.
               chunked: true,//允许分片上传
               chunkSize:2*1024*1024,//每个分片大小
               auto: true,//是否自动上传
               duplicate:true,//去除重复
               fileNumLimit:20,//上传文件个数限制  
               fileSingleSizeLimit:20*1024*1024, //单个文件大小限制  20M
               accept: {
                title: '文字描述',//文字描述
                extensions: 'png,3gp,mp4,rmvb,mov,avi,m4v,wmv',//上传文件后缀
                mimeTypes: 'image/*,video/*,audio/*,application/*'//上传文件类型
               }
        });
        uploader.on('uploadStart', function (file) {
              alert("这是文件上传前的操作函数");
        });
        $("#ctlBtn").click(function () {
            alert("要使用手动上传请设置参数");
          //  uploader.upload();//这是将参数配置auto设置 false 手动上传
        });
        uploader.on( 'fileQueued', function( file ) { //文件加入队列后触发
             var $list = $("#fileList"),
             $li = $(
             '<div id="' + file.id + '" class="file-item thumbnail">' + '<img>'+ '<div class="info">' + file.name + '</div>' + '</div>'
             ),
             $img = $li.find('img');         
             // $list为容器jQuery实例
             $list.append( $li );  
             // 创建缩略图
             uploader.makeThumb( file, function( error, src ) { //src base_64位
                 if ( error ) {
                     $img.replaceWith('<span>不能预览</span>');
                     return;
                 }
               
                 $img.attr( 'src', src );
             }, 100, 100 ); //100x100为缩略图尺寸
        });
        // 文件上传过程中创建进度实时显示。
        uploader.on( 'uploadProgress', function( file, percentage ) {
            var ss=(percentage*100)+"%";
            $("#ss").text(ss);
        });
           
        // 文件上传成功
        uploader.on( 'uploadSuccess', function( file, res ) {
             alert("这是文件上传成功的操作函数");
             console.log(res.filePaht);//这里可以得到上传后的文件路径
        });
 
    });
</script>

php代码

<?php
 
/**
 * @Author: Administrator
 * @Date:   2017-11-22 17:17:48
 * @Last Modified by:   liao
 * @Last Modified time: 2018-01-16 21:23:29
 */
 
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");
//字符串转码 无论是什么文件名称,先unicode转utf8 unicode转utf8 注意$str='"..."',内部双引号,外部单引号 对于变量$str='..',我们需要处理'"'.$str.'"',处理后成一个新变量
function unicode2utf8($str){
  if(!$str) return $str;
  $decode = json_decode($str);
  if($decode) return $decode;
  $str = '["' . $str . '"]';
  $decode = json_decode($str);
  if(count($decode) == 1){
  return $decode[0];
  }
  return $str;
} 
 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_");
  }
  //-------------------------------------------------------
    $fileName=unicode2utf8('"'.$fileName.'"');
    $fileName= iconv("UTF-8", "GBK", $fileName);//防止fopen语句失效
    //-----------------------------------------------------------------------
  $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,
    'fileSuffixes'=>$pathInfo['extension'],
    ];
  
   echo json_encode($response);
   exit();
  }
  
  // Return Success JSON-RPC response
  die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
 
?>

这里是webuploader 的使用方法

 

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script type="text/javascript" src="jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="webuploader.js"></script>
    <style type="text/css">
      .webuploader-container {
            position: relative;
        }
        .webuploader-element-invisible {
            position: absolute !important;
            clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
            clip: rect(1px,1px,1px,1px);
        }
        .webuploader-pick {
            position: relative;
            display: inline-block;
            cursor: pointer;
            background: #00b7ee;
            padding: 10px 15px;
            color: #fff;
            text-align: center;
            border-radius: 3px;
            overflow: hidden;
        }
        .webuploader-pick-hover {
            background: #00a2d4;
        }
 
        .webuploader-pick-disable {
            opacity: 0.6;
            pointer-events:none;
        }
    </style>
</head>
<body>
    <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>
     <div id="fileList"></div>
     <div id="ss"></div>
</body>
</html>

  JavaScript代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<script type="text/javascript">
    jQuery(function() {
        var  uploader;
        uploader = WebUploader.create({
               resize: false// 不压缩image     
               swf: 'uploader.swf',// swf文件路径    
               server: 'upload.php'// 文件接收服务端。 
               pick: '#picker',// 选择文件的按钮。可选。内部根据当前运行是创建,可能是input元素,也可能是flash.
               chunked: true,//允许分片上传
               chunkSize:2*1024*1024,//每个分片大小
               auto: true,//是否自动上传
               duplicate:true,//去除重复
               fileNumLimit:20,//上传文件个数限制  
               fileSingleSizeLimit:20*1024*1024, //单个文件大小限制  20M
               accept: {
                title: '文字描述',//文字描述
                extensions: 'png,3gp,mp4,rmvb,mov,avi,m4v,wmv',//上传文件后缀
                mimeTypes: 'image/*,video/*,audio/*,application/*'//上传文件类型
               }
        });
        uploader.on('uploadStart'function (file) {
              alert("这是文件上传前的操作函数");
        });
        $("#ctlBtn").click(function () {
            alert("要使用手动上传请设置参数");
          //  uploader.upload();//这是将参数配置auto设置 false 手动上传
        });
        uploader.on( 'fileQueued'function( file ) { //文件加入队列后触发
             var $list = $("#fileList"),
             $li = $(
             '<div id="' + file.id + '" class="file-item thumbnail">' '<img>''<div class="info">' + file.name + '</div>' '</div>'
             ),
             $img = $li.find('img');         
             // $list为容器jQuery实例
             $list.append( $li );  
             // 创建缩略图
             uploader.makeThumb( file, function( error, src ) { //src base_64位
                 if ( error ) {
                     $img.replaceWith('<span>不能预览</span>');
                     return;
                 }
               
                 $img.attr( 'src', src );
             }, 100, 100 ); //100x100为缩略图尺寸
        });
        // 文件上传过程中创建进度实时显示。
        uploader.on( 'uploadProgress'function( file, percentage ) {
            var ss=(percentage*100)+"%";
            $("#ss").text(ss);
        });
           
        // 文件上传成功
        uploader.on( 'uploadSuccess'function( file, res ) {
             alert("这是文件上传成功的操作函数");
             console.log(res.filePaht);//这里可以得到上传后的文件路径
        });
 
    });
</script>
原文地址:https://www.cnblogs.com/gaosf/p/14111216.html