Thinkphp拖拽上传文件-使用webuploader插件(自己改动了一些地方)——分片上传

  1. html页面:    
  2. <!DOCTYPE html>    
  3. <html class="js cssanimations">    
  4. <head>    
  5. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">    
  6. <title>Thinkphp拖拽上传文件-使用webuploader插件</title>    
  7. <include file="Inc/css" />    
  8. <link rel="stylesheet" href="__PUBLIC__/webuploader/xb-webuploader.css">    
  9. <script src="__PUBLIC__/js/jquery.min.js"></script>    
  10. <script src="__PUBLIC__/webuploader/webuploader.min.js"></script>    
  11. </head>    
  12. <body>    
  13. <div class="admin-content">    
  14. <form action="{:U('Mafull/webuploader')}" method="post" >    
  15.     <div id="upload-57c79f4938104" class="xb-uploader">    
  16.         <input type="hidden"  name="image" id="image">    
  17.         <div class="queueList">    
  18.             <div class="placeholder" style="padding: 20px">    
  19.                 <div class="filePicker"></div>    
  20.             </div>    
  21.         </div>    
  22.         <div class="statusBar" style="display:none;">    
  23.             <div class="progress">    
  24.                 <span class="text">0%</span>    
  25.                 <span class="percentage"></span>    
  26.             </div>    
  27.             <div class="info"></div>    
  28.                 <!-- <div class="btns">    
  29.                     <div class="uploadBtn">开始上传</div>    
  30.                 </div>-->    
  31.              </div>    
  32.         </div>    
  33.                             
  34.                             
  35.     </div>    
  36. </form>    
  37. </div>    
  38.   
  39.   
  40.   
  41. <script>  
  42. /*上传文件操作  开始*/  
  43. jQuery(function() {  
  44.     var $ = jQuery,    // just in case. Make sure it's not an other libaray.  
  45.   
  46.         $wrap = $("#upload-57c79f4938104"),  
  47.   
  48.         // 图片容器  
  49.         $queue = $('<ul class="filelist"></ul>')  
  50.             .appendTo( $wrap.find('.queueList') ),  
  51.   
  52.         // 状态栏,包括进度和控制按钮  
  53.         $statusBar = $wrap.find('.statusBar'),  
  54.   
  55.         // 文件总体选择信息。  
  56.         $info = $statusBar.find('.info'),  
  57.   
  58.         // 上传按钮  
  59.         $upload = $wrap.find('.uploadBtn'),  
  60.   
  61.         // 没选择文件之前的内容。  
  62.         $placeHolder = $wrap.find('.placeholder'),  
  63.   
  64.         // 总体进度条  
  65.         $progress = $statusBar.find('.progress').hide(),  
  66.   
  67.         // 添加的文件数量  
  68.         fileCount = 0,  
  69.   
  70.         // 添加的文件总大小  
  71.         fileSize = 0,  
  72.   
  73.         // 优化retina, 在retina下这个值是2  
  74.         ratio = window.devicePixelRatio || 1,  
  75.   
  76.         // 缩略图大小  
  77.         thumbnailWidth = 110 * ratio,  
  78.         thumbnailHeight = 110 * ratio,  
  79.   
  80.         // 可能有pedding, ready, uploading, confirm, done.  
  81.         state = 'pedding',  
  82.   
  83.         // 所有文件的进度信息,key为file id  
  84.         percentages = {},  
  85.   
  86.         supportTransition = (function(){  
  87.             var s = document.createElement('p').style,  
  88.                 r = 'transition' in s ||  
  89.                       'WebkitTransition' in s ||  
  90.                       'MozTransition' in s ||  
  91.                       'msTransition' in s ||  
  92.                       'OTransition' in s;  
  93.             s = null;  
  94.             return r;  
  95.         })(),  
  96.   
  97.         // WebUploader实例  
  98.         uploader;  
  99.   
  100.     if ( !WebUploader.Uploader.support() ) {  
  101.         alert( 'Web Uploader 不支持您的浏览器!如果你使用的是IE浏览器,请尝试升级 flash 播放器');  
  102.         throw new Error( 'WebUploader does not support the browser you are using.' );  
  103.     }  
  104.   
  105.     // 实例化  
  106.     uploader = WebUploader.create({  
  107.           
  108.         auto: true,// 选完文件后,是否自动上传。  
  109.         compress:false,  
  110.         pick: {  
  111.             id: "#upload-57c79f4938104 .filePicker",  
  112.             label: '点击选择文件',  
  113.             multiple : true  
  114.         },  
  115.         dnd: "#upload-57c79f4938104 .queueList",  
  116.         paste: document.body,  
  117.          
  118.         // swf文件路径  
  119.         swf: BASE_URL + '/Uploader.swf',  
  120.   
  121.         disableGlobalDnd: true,// [可选] [默认值:false]是否禁掉整个页面的拖拽功能,如果不禁用,图片拖进来的时候会默认被浏览器打开。  
  122.   
  123.         server: "__URL__/ajax_upload",  
  124.         chunked: true,//是否切片  
  125.         chunkSize:10*1024*1024,  
  126.         fileNumLimit: 1,  
  127.         fileSizeLimit: 1024 * 1024 * 1024,    // 1G  
  128.         fileSingleSizeLimit: 1024 * 1024 * 1024    // 1G  
  129.     });  
  130.   
  131.     // 当有文件添加进来时执行,负责view的创建  
  132.     function addFile( file ) {  
  133.         var $li = $( '<li id="' + file.id + '">' +  
  134.                 '<class="title">' + file.name + '</p>' +  
  135.                 '<class="imgWrap"></p>'+  
  136.                 '<class="progress"><span></span></p>' +  
  137.                 '</li>' ),  
  138.   
  139.             $btns = $('<div class="file-panel">' +  
  140.                 '<span class="cancel">删除</span>' +  
  141.                 '<span class="rotateRight">向右旋转</span>' +  
  142.                 '<span class="rotateLeft">向左旋转</span></div>').appendTo( $li ),  
  143.             $prgress = $li.find('p.progress span'),  
  144.             $wrap = $li.find( 'p.imgWrap' ),  
  145.             $info = $('<class="error"></p>'),  
  146.   
  147.             showError = function( code ) {  
  148.                 switch( code ) {  
  149.                     case 'exceed_size':  
  150.                         text = '文件大小超出';  
  151.                         break;  
  152.   
  153.                     case 'interrupt':  
  154.                         text = '上传暂停';  
  155.                         break;  
  156.   
  157.                     default:  
  158.                         text = '上传失败,请重试';  
  159.                         break;  
  160.                 }  
  161.   
  162.                 $info.text( text ).appendTo( $li );  
  163.             };  
  164.   
  165.         if ( file.getStatus() === 'invalid' ) {  
  166.             showError( file.statusText );  
  167.         } else {  
  168.             // @todo lazyload  
  169.             $wrap.text( '预览中' );  
  170.             uploader.makeThumb( file, function( error, src ) {  
  171.                 if ( error ) {  
  172.                     $wrap.text( '不能预览' );  
  173.                     return;  
  174.                 }  
  175.   
  176.                 var img = $('<img src="'+src+'">');  
  177.                 $wrap.empty().append( img );  
  178.             }, thumbnailWidth, thumbnailHeight );  
  179.   
  180.             percentages[ file.id ] = [ file.size, 0 ];  
  181.             file.rotation = 0;  
  182.         }  
  183.   
  184.         file.on('statuschange', function( cur, prev ) {  
  185.             if ( prev === 'progress' ) {  
  186.                 $prgress.hide().width(0);  
  187.             } else if ( prev === 'queued' ) {  
  188.                 $li.off( 'mouseenter mouseleave' );  
  189.                 $btns.remove();  
  190.             }  
  191.   
  192.             // 成功  
  193.             if ( cur === 'error' || cur === 'invalid' ) {  
  194.                 console.log( file.statusText );  
  195.                 showError( file.statusText );  
  196.                 percentages[ file.id ][ 1 ] = 1;  
  197.             } else if ( cur === 'interrupt' ) {  
  198.                 showError( 'interrupt' );  
  199.             } else if ( cur === 'queued' ) {  
  200.                 percentages[ file.id ][ 1 ] = 0;  
  201.             } else if ( cur === 'progress' ) {  
  202.                 $info.remove();  
  203.                 $prgress.css('display', 'block');  
  204.             } else if ( cur === 'complete' ) {  
  205.                 $li.append( '<span class="success"></span>' );  
  206.             }  
  207.   
  208.             $li.removeClass( 'state-' + prev ).addClass( 'state-' + cur );  
  209.         });  
  210.   
  211.         $li.on( 'mouseenter', function() {  
  212.             $btns.stop().animate({height: 30});  
  213.         });  
  214.   
  215.         $li.on( 'mouseleave', function() {  
  216.             $btns.stop().animate({height: 0});  
  217.         });  
  218.   
  219.         $btns.on( 'click', 'span', function() {  
  220.             var index = $(this).index(),  
  221.                 deg;  
  222.   
  223.             switch ( index ) {  
  224.                 case 0:  
  225.                     uploader.removeFile( file );  
  226.                     return;  
  227.   
  228.                 case 1:  
  229.                     file.rotation += 90;  
  230.                     break;  
  231.   
  232.                 case 2:  
  233.                     file.rotation -= 90;  
  234.                     break;  
  235.             }  
  236.   
  237.             if ( supportTransition ) {  
  238.                 deg = 'rotate(' + file.rotation + 'deg)';  
  239.                 $wrap.css({  
  240.                     '-webkit-transform': deg,  
  241.                     '-mos-transform': deg,  
  242.                     '-o-transform': deg,  
  243.                     'transform': deg  
  244.                 });  
  245.             } else {  
  246.                 $wrap.css( 'filter', 'progid:DXImageTransform.Microsoft.BasicImage(rotation='+ (~~((file.rotation/90)%4 + 4)%4) +')');  
  247.                   
  248.             }  
  249.   
  250.   
  251.         });  
  252.   
  253.         $li.appendTo( $queue );  
  254.     }  
  255.   
  256.     // 负责view的销毁  
  257.     function removeFile( file ) {  
  258.         var $li = $('#'+file.id);  
  259.   
  260.         delete percentages[ file.id ];  
  261.         updateTotalProgress();  
  262.         $li.off().find('.file-panel').off().end().remove();  
  263.     }  
  264.   
  265.     function updateTotalProgress() {  
  266.         var loaded = 0,  
  267.             total = 0,  
  268.             spans = $progress.children(),  
  269.             percent;  
  270.   
  271.         $.each( percentages, function( k, v ) {  
  272.             total += v[ 0 ];  
  273.             loaded += v[ 0 ] * v[ 1 ];  
  274.         } );  
  275.   
  276.         percent = total ? loaded / total : 0;  
  277.   
  278.         spans.eq( 0 ).text( Math.round( percent * 100 ) + '%' );  
  279.         spans.eq( 1 ).css( 'width', Math.round( percent * 100 ) + '%' );  
  280.         updateStatus();  
  281.     }  
  282.   
  283.     function updateStatus() {  
  284.         var text = '', stats;  
  285.   
  286.         if ( state === 'ready' ) {  
  287.             text = '选中' + fileCount + '个文件,共' +  
  288.                     WebUploader.formatSize( fileSize ) + '。';  
  289.                       
  290.         } else if ( state === 'confirm' ) {  
  291.             stats = uploader.getStats();  
  292.             if ( stats.uploadFailNum ) {  
  293.                 text = '已成功上传' + stats.successNum+ '个文件,'+  
  294.                     stats.uploadFailNum + '个上传失败,<class="retry" href="#">重新上传</a>失败文件或<class="ignore" href="#">忽略</a>'  
  295.             }  
  296.   
  297.         } else {  
  298.             stats = uploader.getStats();  
  299.             if(stats.successNum==0){  
  300.             text="";  
  301.         }  
  302.         else  
  303.         {  
  304.             text = '共' + fileCount + '个(' +  
  305.                     WebUploader.formatSize( fileSize )  +  
  306.                     '),已上传' + stats.successNum + '个<br /><style="font-size:22px; color:#0b8cec;font-weight: bold;">已上传成功,点击“下一步”吧</p>';  
  307.               }  
  308.   
  309.             if ( stats.uploadFailNum ) {  
  310.                 text += ',失败' + stats.uploadFailNum + '个';  
  311.             }  
  312.         }  
  313.         var txtSize=WebUploader.formatSize(fileSize);  
  314.         if(txtSize=="0B"){  
  315.             $("#upload-57c79f4938104 input[name='size']").val('');  
  316.         }  
  317.         else{  
  318.             $("#upload-57c79f4938104 input[name='size']").val(txtSize);  
  319.         }  
  320.         $info.html( text );  
  321.     }  
  322.   
  323.     uploader.onUploadAccept=function(object ,ret){  
  324.         if(ret.error_info){  
  325.             fileError=ret.error_info;  
  326.             return false;  
  327.         }  
  328.     }  
  329.   
  330.     uploader.onUploadSuccess=function(file ,response){  
  331.         fileName=response.filePath;  
  332.         filePixels=response.filePixels;  
  333.     }  
  334.     uploader.onUploadError=function(file){  
  335.         alert(fileError);  
  336.     }  
  337.   
  338.     function setState( val ) {  
  339.         var file, stats;  
  340.         if ( val === state ) {  
  341.             return;  
  342.         }  
  343.   
  344.         $upload.removeClass( 'state-' + state );  
  345.         $upload.addClass( 'state-' + val );  
  346.         state = val;  
  347.   
  348.         switch ( state ) {  
  349.             case 'pedding':  
  350.                 $placeHolder.removeClass( 'element-invisible' );  
  351.                 $queue.parent().removeClass('filled');  
  352.                 $queue.hide();  
  353.                 $statusBar.addClass( 'element-invisible' );  
  354.                 uploader.refresh();  
  355.                 break;  
  356.   
  357.             case 'ready':  
  358.                 $placeHolder.addClass( 'element-invisible' );  
  359.                 $( "#upload-57c79f4938104 .filePicker2" ).removeClass( 'element-invisible');  
  360.                 $queue.parent().addClass('filled');  
  361.                 $queue.show();  
  362.                 $statusBar.removeClass('element-invisible');  
  363.                 uploader.refresh();  
  364.                 break;  
  365.   
  366.             case 'uploading':  
  367.                 $( "#upload-57c79f4938104 .filePicker2" ).addClass( 'element-invisible' );  
  368.                 $progress.show();  
  369.                 $upload.text( '暂停上传' );  
  370.                 break;  
  371.   
  372.             case 'paused':  
  373.                 $progress.show();  
  374.                 $upload.text( '继续上传' );  
  375.                 break;  
  376.   
  377.             case 'confirm':  
  378.                 $progress.hide();  
  379.                 $upload.text( '开始上传' ).addClass( 'disabled' );  
  380.   
  381.                 stats = uploader.getStats();  
  382.                 if ( stats.successNum && !stats.uploadFailNum ) {  
  383.                     setState( 'finish' );  
  384.                     return;  
  385.                 }  
  386.                 break;  
  387.             case 'finish':  
  388.                 stats = uploader.getStats();  
  389.                 if ( stats.successNum ) {  
  390.                     $("#upload-57c79f4938104 input[name='image']").val(fileName);  
  391.                     if(filePixels=="*px"){  
  392.                         $("#upload-57c79f4938104 input[name='pixels']").val();  
  393.                     }  
  394.                     else  
  395.                     {  
  396.                          $("#upload-57c79f4938104 input[name='pixels']").val(filePixels);  
  397.                     }  
  398.                 } else {  
  399.                     // 没有成功的图片,重设  
  400.                     state = 'done';  
  401.                     location.reload();  
  402.                 }  
  403.                 break;  
  404.         }  
  405.         updateStatus();  
  406.     }  
  407.   
  408.     uploader.onUploadProgress = function( file, percentage ) {  
  409.         var $li = $('#'+file.id),  
  410.             $percent = $li.find('.progress span');  
  411.   
  412.         $percent.css( 'width', percentage * 100 + '%' );  
  413.         percentages[ file.id ][ 1 ] = percentage;  
  414.         updateTotalProgress();  
  415.     };  
  416.   
  417.     uploader.onFileQueued = function( file ) {  
  418.         fileCount++;  
  419.         fileSize += file.size;  
  420.   
  421.         if ( fileCount === 1 ) {  
  422.             $placeHolder.addClass( 'element-invisible' );  
  423.             $statusBar.show();  
  424.         }  
  425.   
  426.         addFile( file );  
  427.         setState( 'ready' );  
  428.         updateTotalProgress();  
  429.     };  
  430.   
  431.     uploader.onFileDequeued = function( file ) {  
  432.         fileCount--;  
  433.         fileSize -= file.size;  
  434.   
  435.         if ( !fileCount ) {  
  436.             setState( 'pedding' );  
  437.         }  
  438.   
  439.         removeFile( file );  
  440.         updateTotalProgress();  
  441.   
  442.     };  
  443.   
  444.     uploader.on( 'all', function( type ) {  
  445.         var stats;  
  446.         switch( type ) {  
  447.             case 'uploadFinished':  
  448.                 setState( 'confirm' );  
  449.                 break;  
  450.   
  451.             case 'startUpload':  
  452.                 setState( 'uploading' );  
  453.                 break;  
  454.   
  455.             case 'stopUpload':  
  456.                 setState( 'paused' );  
  457.                 break;  
  458.   
  459.         }  
  460.     });  
  461.   
  462.     uploader.onError = function( code ) {  
  463.         alert( 'Eroor: ' + code );  
  464.     };  
  465.   
  466.     $upload.on('click', function() {  
  467.         if ( $(this).hasClass( 'disabled' ) ) {  
  468.             return false;  
  469.         }  
  470.   
  471.         if ( state === 'ready' ) {  
  472.             uploader.upload();  
  473.         } else if ( state === 'paused' ) {  
  474.             uploader.upload();  
  475.         } else if ( state === 'uploading' ) {  
  476.             uploader.stop();  
  477.         }  
  478.     });  
  479.   
  480.     $info.on( 'click', '.retry', function() {  
  481.         uploader.retry();  
  482.     } );  
  483.   
  484.     $info.on( 'click', '.ignore', function() {  
  485.         alert( 'todo' );  
  486.     } );  
  487.   
  488.     $upload.addClass( 'state-' + state );  
  489.     updateTotalProgress();  
  490. });  
  491. /*上传文件操作  结束*/  
  492. </script>  
  493.   
  494. <script>  
  495.     var BASE_URL = '__PUBLIC__/webuploader';  
  496. </script>  
  497. <script src="__PUBLIC__/webuploader/webuploader.min.js"></script>  
  498.   
  499. </body>  
  500. </html>  
    1. php:MafullController.class.php中写入上传方法:    
    2.     /**  
    3.      * webuploader 上传demo  
    4.      */    
    5.     public function webuploader(){    
    6.         // 如果是post提交则显示上传的文件 否则显示上传页面    
    7.         if(IS_POST){    
    8.             $image=I('post.image');    
    9.             // 判断是否有文件上传    
    10.             if (empty($image)) {    
    11.                 die('没有上传文件');    
    12.             }    
    13.             echo '上传成功路径为:'.$image;    
    14.         }else{    
    15.             $this->display();    
    16.         }    
    17.     }    
    18.   
    19.   
    20. //切片上传方法  
    21.     public function ajax_upload()  
    22.     {  
    23.         //故意写一个过期时间目的也是让浏览器去重新读取页面内容.你要知道,浏览器一般情况下去保存你访问过的页面的大部分内容,你第二次访问的时候,保存的内容(称为缓存)浏览器就不需要再向服务器请求了,这样节约时间,也减轻了服务器的负担.  
    24.         header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");//内容过期时间   
    25.         header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");//标记内容最后修改时间  
    26.         header("Cache-Control: no-store, no-cache, must-revalidate");//强制不缓存  
    27.         header("Cache-Control: post-check=0, pre-check=0", false);//Internet Explorer 5对于HTTP头信息使用两种新的时间间隔指示  
    28.         header("Pragma: no-cache");//禁止本页被缓存  
    29.   
    30.         //$_SERVER['REQUEST_METHOD']这个变量表示的是表单提交数据的方式,get或者post  
    31.         if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {  
    32.             exit; // 完成预检CORS请求  
    33.         }  
    34.         if ( !empty($_REQUEST[ 'debug' ]) ) {  
    35.             $random = rand(0, intval($_REQUEST[ 'debug' ]) );  
    36.             if ( $random === 0 ) {  
    37.                 header("HTTP/1.0 500 Internal Server Error");  
    38.                 exit;  
    39.             }  
    40.         }  
    41.   
    42.         // 5分钟执行时间  
    43.         @set_time_limit(5 * 60);  
    44.         $targetDir = 'PublicUpload'.DIRECTORY_SEPARATOR.'file_material_tmp';  
    45.         $uploadDir = 'PublicUpload'.DIRECTORY_SEPARATOR.'file_material';  
    46.         $cleanupTargetDir = true; // 是否删除以前的临时文件内容  
    47.         $maxFileAge = 5 * 3600; // 临时文件时间(以秒为单位)  
    48.           
    49.         // 获取文件名  
    50.         if (!file_exists($targetDir)) {  
    51.             @mkdir($targetDir);//mkdir() 函数创建目录。  
    52.         }  
    53.         // 创建目标目录  
    54.         if (!file_exists($uploadDir)) {  
    55.             @mkdir($uploadDir);//mkdir() 函数创建目录。  
    56.         }  
    57.           
    58.         // 获取文件名  
    59.         if (isset($_REQUEST["name"])) {  
    60.             $fileName = $_REQUEST["name"];  
    61.         } elseif (!empty($_FILES)) {  
    62.             $fileName = $_FILES["file"]["name"];  
    63.         } else {  
    64.             $fileName = uniqid("file_");  
    65.         }  
    66.         $fileName=iconv("UTF-8", "gb2312", $fileName);  
    67.         $oldName = $fileName;  
    68.         $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;  
    69.           
    70.           
    71.         // 取得chunk和chunks  
    72.         $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;  
    73.         $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;  
    74.           
    75.           
    76.         // 删除以前的临时文件内容,如:file_material_tmp文件夹内的文件  
    77.         if ($cleanupTargetDir) {  
    78.             if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {  
    79.             //is_dir -- 判断给定文件名是否是一个目录  
    80.             //opendir()函数的作用是:打开目录句柄。  
    81.                 die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');  
    82.             }  
    83.             while (($file = readdir($dir)) !== false) {//readdir ,readdir_r,----读一个目录  
    84.                 $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;  
    85.                 // 如果临时文件是当前文件,继续下一步  
    86.                 if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {  
    87.                     continue;  
    88.                 }  
    89.                 // 删除临时文件,如果它早于最大年龄,并且不是当前文件  
    90.                 //preg_match() 函数用于进行正则表达式匹配,成功返回 1 ,否则返回 0   
    91.                 if (preg_match('/.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {  
    92.                     //filemtime() 函数返回文件内容上次的修改时间。若成功,则时间以 Unix 时间戳的方式返回。若失败,则返回 false。  
    93.                     @unlink($tmpfilePath);//unlink() 函数删除文件。  
    94.                 }  
    95.             }  
    96.             closedir($dir);  
    97.         }  
    98.         // 打开临时文件  
    99.         if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {  
    100.               
    101.             die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');  
    102.         }  
    103.           
    104.         if (!empty($_FILES)) {  
    105.             if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {  
    106.                 die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');  
    107.             }  
    108.             // 读取二进制输入流并将其附加到临时文件  
    109.             if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {  
    110.                 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');  
    111.             }  
    112.         } else {  
    113.             if (!$in = @fopen("php://input", "rb")) {  
    114.                 die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');  
    115.             }  
    116.         }  
    117.         while ($buff = fread($in, 4096)) {  
    118.             fwrite($out, $buff);  
    119.         }  
    120.         @fclose($out);  
    121.         @fclose($in);  
    122.         rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");  
    123.         $index = 0;  
    124.         $done = true;  
    125.         for( $index = 0; $index < $chunks; $index++ ) {  
    126.             if ( !file_exists("{$filePath}_{$index}.part") ) {  
    127.                 $done = false;  
    128.                 break;  
    129.             }  
    130.         }  
    131.   
    132.         if ( $done ) {  
    133.         $pathInfo = pathinfo($fileName);  
    134.         $hashStr = substr(md5($pathInfo['basename']),8,16);  
    135.         $hashName = time() . $hashStr . '.' .$pathInfo['extension'];  
    136.         $uploadPath = $uploadDir . DIRECTORY_SEPARATOR .$hashName;  
    137.   
    138.         if (!$out = @fopen($uploadPath, "wb")) {  
    139.             die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');  
    140.         }  
    141.         if ( flock($out, LOCK_EX) ) {  
    142.             for( $index = 0; $index < $chunks; $index++ ) {  
    143.                 if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {  
    144.                     break;  
    145.                 }  
    146.                 while ($buff = fread($in, 4096)) {  
    147.                     fwrite($out, $buff);  
    148.                 }  
    149.                 @fclose($in);  
    150.                 @unlink("{$filePath}_{$index}.part");  
    151.             }  
    152.             flock($out, LOCK_UN);  
    153.         }  
    154.         @fclose($out);  
    155.           
    156.         //$data=array();  
    157.         //$data['name']=$uploadPath;//PublicUploadfile_material14793553561ee00a15b8a23204.jpg  
    158.         //echo json_encode($data);`  
    159.           
    160.         //exit;  
    161.         //$data['name']=trim($uploadPath);  
    162.         $list = getimagesize($uploadPath);  
    163.         $data['pixels']=trim($list[0]."*".$list[1].'px');  
    164.         $response = array(  
    165.                 'success'=>true,  
    166.                 'oldName'=>$oldName,  
    167.                 'filePath'=>trim(str_replace("\","/",substr($uploadPath,6))),  
    168.                 'fileSize'=>$data['size'],  
    169.                 'fileSuffixes'=>$pathInfo['extension'],  
    170.                 'file_id'=>$data['id'],  
    171.                 'filePixels'=>$data['pixels'],  
    172.             );  
    173.   
    174.         die(json_encode($response));  
    175.         }  
    176.   
    177.         // 返回成功JSON-RPC响应  
    178.         die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');  
    179.   
    180.     } 
原文地址:https://www.cnblogs.com/ghjbk/p/7443835.html