webuploader分片文件上传

摘要:
首先,将插件放在公共html代码下select file开始上传˃上传文件;Functionuploadfiles{$(function()){var$list=$(“#the_”+ids);$btn=$(“#btn_”+id);varuploader=WebUploader.create({auto:true,resize:false,//不压缩imageswf:'/WebUploader/uploader.swf',//swf文件路径服务器:'{:url(“admin/upload/uploadFile”)}',//文件接收服务器。可选分块:true,//是否处理大文件上传分块大小:5*1024*1024,//分割上传,每个切片2M,默认值为5M/fileSizeLimit:6*1024*1024*104,//所有文件的总大小限制为6GfileSingleSizeLlimit:10*1024*104*1024,//单个文件大小限制为5GformData:{folder:folder/用户定义的参数},})}控制器代码publicfunctionuploadFile(){header;header;header;header;header,header;$folder=input;if{exit;//finishpreflightCORRequestshere}if(!Empty){$random=rand;if{header;exit;}}//header//exit;//5分钟执行时间集_时间限制;//取消对这段上传时间的注释;//设置$targetDir='./公共'.DIRECTORY_SEPARATOR.'文件_材料_ tmp';//如果{$uploadDir=“./Public”.directory_SEPARATOR.'file_material'.directory_SEPARATOR.$folder.directory_SEPARATOR.date;}否则{$uploadDir=‘./Public’.directory.SEPARATOR.‘file_material’.directory_SEPARATOR.date;//合并分区目录}$cleanupTargetDir=true//Removeoldfiles$maxFileAge=5*3600;//Tempfileageinseconds//创建目标目录(!

首先将插件放在 public下  

webuploader分片文件上传第1张

html代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js">
    </script>
    <script src="/webuploader/webuploader.js"></script>
    <link rel ="slylesheet" type="text/css" href="/webuploader/webuploader.css">

</head>
<body>

<div class="demo">
    <div id="uploadfile">
        <!--用来存放文件信息-->
        <div id="the_2655" class="uploader-list"></div>
        <div class="form-group form-inline">
            <div id="pick_2655" style="float:left">选择文件</div>
            <button id="Btn_2655" class="btn btn-default" style="padding: 5px 10px;border-radius: 3px;">开始上传</button>
        </div>
    </div>
</div>


</body>
</html>
<script>

    uploadfiles(2655,"files");

    function uploadfiles(ids,folder) {
        $(function(){
                var $list = $("#the_"+ids);
                $btn = $("#Btn_"+ids);
                var uploader = WebUploader.create({

                    auto:true,
                    resize: false, // 不压缩image
                    swf: '/webuploader/uploader.swf', // swf文件路径
                    server: '{:url("admin/upimg/uploadFile")}', // 文件接收服务端。
                    pick: "#pick_"+ids, // 选择文件的按钮。可选
                    chunked: true, //是否要分片处理大文件上传
                    chunkSize:5*1024*1024, //分片上传,每片2M,默认是5M
                    //fileSizeLimit: 6*1024* 1024 * 1024,    // 所有文件总大小限制 6G
                    fileSingleSizeLimit: 10*1024* 1024 * 1024,    // 单个文件大小限制 5 G
                    formData: {
                        folder:folder  //自定义参数
                    },
                });
            }
        )};
</script>

 webuploader分片文件上传第2张webuploader分片文件上传第3张

控制器代码

    public function uploadFile(){
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Content-type: text/html; charset=gbk32");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        $folder = input('folder');
        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 = './Public'.DIRECTORY_SEPARATOR.'file_material_tmp';            //存放分片临时目录
        if($folder){
            $uploadDir = './Public'.DIRECTORY_SEPARATOR.'file_material'.DIRECTORY_SEPARATOR.$folder.DIRECTORY_SEPARATOR.date('Ymd');
        }else{
            $uploadDir = './Public'.DIRECTORY_SEPARATOR.'file_material'.DIRECTORY_SEPARATOR.date('Ymd');    //分片合并存放目录
        }

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

        // Create target dir
        if (!file_exists($targetDir)) {
            mkdir($targetDir,0777,true);
        }
        // Create target dir
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir,0777,true);
        }
        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        $oldName = $fileName;

        $fileName = iconv('UTF-8','gb2312',$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 directory111."}, "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}" || $tmpfilePath == "{$filePath}_{$chunk}") {
                    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}", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream222."}, "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 file333."}, "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 stream444."}, "id" : "id"}');
            }
        } else {
            if (!$in = fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream555."}, "id" : "id"}');
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        fclose($out);
        fclose($in);
        rename("{$filePath}_{$chunk}", "{$filePath}_{$chunk}");
        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}") ) {
                $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 stream666."}, "id" : "id"}');
            }
            //flock($hander,LOCK_EX)文件锁
            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = fopen("{$filePath}_{$index}", "rb")) {
                        break;
                    }
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    fclose($in);
                    unlink("{$filePath}_{$index}");
                }
                flock($out, LOCK_UN);
            }
            fclose($out);
            $response = [
                'success'=>true,
                'oldName'=>$oldName,
                'filePath'=>$uploadPath,
//                'fileSize'=>$data['size'],
                'fileSuffixes'=>$pathInfo['extension'],          //文件后缀名
//                'file_id'=>$data['id'],
            ];
            return json($response);
        }

        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }

 

免责声明:文章转载自《webuploader分片文件上传》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Android开发之AIDL的使用一--跨应用启动Servicejava连接数据库时的报错下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

WebUploader在IE9中文件选择按钮点击没反应

一、问题:   最近做的公司项目里,用户环境一直用的火狐,但是实际的用户群体都是银行人员   政府部门怎么也要用 IE,而且还有一些用的IE版本是古董版本IE9   IE9 相比 IE8 多了图像渲染等,无法兼容低版本的页面   项目前台用的是 easyui,兼容到IE9还是可以的,但是项目中使用的百度的文件上传插件【WebUpLoader】   在 I...

webuploader上传文件,图片

WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。官方地址:http://fex.baidu.com/webuploader/ 1. 引入资源 使用Web Uploader文件上传需要引入三种资源:JS, CSS, SWF。 <!--引入CSS--> <li...

webuploader在IE8/9下上传遇到的两个问题

最近在做图片上传功能。 点击一个按钮,弹出一个iframe,它是百度的webuploader插件 在点击关闭按钮时,IE9下总是会报错:__flash__removeCallback未定义错误 解决办法很简单,就是在关闭前直接清空含有此flash控件的dom元素。 原因在以下两篇博文里:http://blog.csdn.net/lanfeng330/art...

百度开源上传组件webuploader 可上传多文件并带有进度条

//上传多文件 functionUploadMultiFile() { var uploader =WebUploader.create({ //选完文件后,是否自动上传。 auto: true, //swf文件路径 swf...

对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)

首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUploader是由Baidu WebFE(FEX)团队开发的一个简单的以HTML5为主,FLASH为辅的现代文件上传组件。在现代的浏览器里面能充分发挥HTML5的优势...

PHP 多图上传,图片批量上传插件,webuploader.js,百度文件上传插件

PHP  多图上传,图片批量上传插件,webuploader.js,百度文件上传插件(案例教程) WebUploader作用:http://fex.baidu.com/webuploader/getting-started.html 使用WebUploader还可以批量上传文件、支持缩略图等等众多参数选项可设置,以及多个事件方法可调用,你可以随心所欲的定制...