php切片上传

admin2年前PHP794

html

    <style>        html {            _overflow-y: scroll        }
        .swfupload {            position: absolute;            z-index: 1;        }
        .mainnav_title {            display: none;        }    </style>    <link rel="stylesheet" href="layui/css/layui.css">    <script src="__ROOT__/Public/Js/jquery-3.7.1.min.js"></script>    <script src="/layui/layui.js"></script>    <script type="text/javascript" src="__ROOT__/Public/Js/swfupload/handlers.js"></script>

    <?php    if($file_types == '*.jpeg;*.jpg;*.png;*.gif') {        $accept_file_types = str_replace([';', '*.'], [',', 'image/'], $file_types);    }elseif($file_types == '*.flv;*.mp4;*.swf') {        $accept_file_types = 'video/mp4';    }    $fileName = date('YmdHis', time()).rand(1000,9999);    ?>    <div class="layui-upload" style="margin: 10px;">        <input type="file" id="fileElem" autocomplete="off" style="display: none;" accept="<?php echo $accept_file_types;?>"></input>        <button type="button" class="layui-btn" id="fileSelect">选择文件</button>&emsp;<span style="color: #FF5722">每次只能上传1个文件,文件大小情况控制在3G内</span>        <div class="layui-upload-list">            <table class="layui-table">                <thead>                    <tr style="width: 15%">                        <th>文件名</th>                        <th style="width: 10%">大小</th>                        <th style="width: 65%">进度</th>                        <th style="width: 10%">状态</th>                </thead>                <tbody id="demoList"></tbody>            </table>        </div>        <button type="button" class="layui-btn" id="upstart">开始上传</button>    </div>    <script>        var fileSelect = document.getElementById("fileSelect"),            fileElem = document.getElementById("fileElem"),            upload_url = '{:U('NewUpload/upload')}&PHPSESSID=<?php echo  $sessid;?>&isadmin=<?php echo $isadmin;?>&userid=<?php echo $userid?>&isthumb=<?php echo $isthumb;?>&addwater=<?php echo intval($watermark_enable);?>&lang=<?php echo $lang;?>&moduleid=<?php echo $moduleid?>';
        fileSelect.addEventListener("click", function(e) {            if (fileElem) {                fileElem.click();                fileElem.addEventListener("change", handleFiles, false);            }            e.preventDefault(); // prevent navigation to "#"        }, false);
        var fileList = [];        var file_size = 3100;
        function handleFiles() {            var filecontent = "";            fileList.push($('#fileElem')[0].files[0])
            for (var i = 0; i < fileList.length; i++) {                // 定义允许上传文件的大小                var filesize = (fileList[i].size / 1024 / 1024).toFixed(1);                if (filesize >= file_size) {                    layer.msg(fileList[i].name + '文件大小超出限制', {                        icon: 2,                        time: 3000                    });                    fileList = "";                    return false;                }                filecontent += '<tr>' +                    '<td>' + fileList[i].name + '</td>' +                    '<td>' + (fileList[i].size / 1024 / 1024).toFixed(1) + 'MB</td>' +                    '<td>' +                    '<div lay-filter="' + fileList[i].lastModified + '_' + i + '" lay-showPercent="true" lay-filter="progress_' + i + '">' +                    '<div lay-percent="0%"></div>' +                    '</div>' +                    '</td>' +                    '<td id="' + fileList[i].lastModified + '_' + i + '">等待上传</td>' +                    '<td style="display:none" id="filepath"></td>' +                    '</tr>';            }            $("#demoList").append(filecontent);        }        //---------------        var upstartBtn = document.getElementById('upstart');        //---------------        const LENGTH = 512 * 1024 * 1;        var start = 0;        var end = start + LENGTH;        var blob;        var blob_num = 1;        var is_stop = 0        var file = null;        var loading;        //-----------------------------        var upload_instance = new Upload();        var fileid = 0;        upstartBtn.onclick = function() {            if (fileList.length == 0) {                layer.msg('请选择文件');                return;            }            for (var i = 0; i < fileList.length; i++) {                fileid = fileList[i].lastModified + '_' + i;                upload_instance.addFileAndSend(fileList[i]);            }            return false;        }
        function Upload() {            //对外方法,传入文件对象            this.addFileAndSend = function(that) {                // loading                loading = layer.load(1, {                    shade: [0.3, '#fff']                });                file = that;                blob = cutFile(file);                sendData(blob, file);                blob_num += 1;            }            //切割文件            function cutFile(file) {                var file_blob = file.slice(start, end);                start = end;                end = start + LENGTH;                return file_blob;            };            //发送文件            function sendData(blob, file) {                var form_data = new FormData();                var total_blob_num = Math.ceil(file.size / LENGTH);                form_data.append('file', blob);                form_data.append('blob_num', blob_num);                form_data.append('total_blob_num', total_blob_num);                form_data.append('file_name', '<?php echo $fileName;?>');                form_data.append('file_full_name', file.name);                //console.log(blob_num);                //console.log(total_blob_num);                $.ajax({                    url: upload_url,                    type: 'post',                    async: true,                    dataType: "json",                    data: form_data,                    contentType: false,                    processData: false,                    success: function(data) {                        //console.log(data);                        if (data['code'] == 1) {                            // 进度条和状态设置                            if (total_blob_num == 1) {                                progress = '100%';                            } else {                                progress = (Math.min(100, (blob_num / total_blob_num) * 100)).toFixed(2) + '%';                            }                            // 进度条                            layui.element.progress(fileid, progress);                            // 状态                            var type = document.getElementById(fileid);                            type.innerText = progress;                            //console.log('progress-----' + progress);                            //继续上传                            if (start < file.size && is_stop === 0) {                                blob = cutFile(file);                                sendData(blob, file);                                blob_num += 1;                            }                            //每次清空                            form_data = "";                        } else if (data['code'] == 2) {                            console.log(data);                            // 进度条                            progress = '100%';                            layui.element.progress(fileid, progress);                            // loading end                             layer.close(loading);                            // 上传成功                            var type = document.getElementById(fileid);                            type.innerText = "上传成功";                            var text = '<span style="display:none">' + data.file_path + '</span><span style="display:none">' + data.file_extension + '</span><span style="display:none">' + data.file_name + '</span>';                            <?php                                if($file_types == '*.jpeg;*.jpg;*.png;*.gif') {                                    echo '$(window.parent.document).find(\'#Main\')[0].contentDocument.getElementById("thumb_pic").setAttribute(\'src\', data.file_full_name);$(window.parent.document).find(\'#Main\')[0].contentDocument.getElementById("thumb").setAttribute(\'value\', data.file_full_name);';                                }elseif($file_types == '*.flv;*.mp4;*.swf') {                                    echo '$(window.parent.document).find(\'#Main\')[0].contentDocument.getElementById("video_path").setAttribute(\'value\', data.file_full_name);';                                }elseif($file_types == '*.zip;*.rar;*.doc;*.ppt') {                                    echo '$(window.parent.document).find(\'#Main\')[0].contentDocument.getElementById("file").setAttribute(\'value\', data.file_full_name);';                                }                            ?>                                                        $("#filepath").append(text);                            //每次清空                            form_data = "";                        }                    },                    error: function(data) {                        // loading end                         layer.close(loading);                        layer.msg('网络错误', {                            icon: 2,                            time: 2000                        });                        return;                    }                })            }        }    </script>

php

<?php
ini_set('memory_limit', -1); //要有足够大的内存来允许处理上传的文件
set_time_limit(0); //防止超时
/**
 * 
 * Upload(附件管理)
 *
 * @package         YOURPHP
 * @author          liuxun QQ:147613338 <admin@yourphp.cn>
 * @copyright       Copyright (c) 2008-2011  (http://www.yourphp.cn)
 * @license         http://www.yourphp.cn/license.txt
 * @version         YourPHP企业网站管理系统 v2.1 2012-10-08 yourphp.cn $
 */
if(!defined("Yourphp")) exit("Access Denied");
class NewUploadAction extends Action {
    private $filepath; //上传目录
    private $tmpPath; //PHP文件临时目录
    private $blobNum; //第几个文件块
    private $totalBlobNum; //文件块总数
    private $fileName; //文件名
    public function __construct($tmpPath, $blobNum, $totalBlobNum, $fileName, $filepath)
    {
    }
    public function upload() {
        // 上传文件
        $uploadDir = './upload';
        $dirDate = date('Y-m-d', time());
        $uploadDir = $uploadDir . '/' . $dirDate;
        if(!is_dir($uploadDir)) mkdir($uploadDir);
        $fileName = $_POST['file_name'];
        $ext = substr(strrchr($_POST['file_full_name'], '.'), 1);
        $fileName = $fileName.'.'.$ext;
        $this->tmpPath = $_FILES['file']['tmp_name'];
        $this->blobNum = $_POST['blob_num'];
        $this->totalBlobNum = $_POST['total_blob_num'];
        $this->fileName = $fileName;
        $this->filepath = $uploadDir;
        $this->moveFile();
        $this->fileMerge();
        $this->apiReturn();
    }
    private function fileMerge()
    {
        $blob = '';
        $blob = file_get_contents($this->filepath . '/' . $this->fileName . '__' . $this->blobNum);
        $res = file_put_contents($this->filepath . '/' . $this->fileName, $blob, FILE_APPEND);
        unset($blob);
        $this->deleteFileBlob();
    }
    //删除文件块
    private function deleteFileBlob()
    {
        for ($i = 1; $i <= $this->totalBlobNum; $i++) {
            @unlink($this->filepath . '/' . $this->fileName . '__' . $i);
        }
    }
    private function moveFile()
    {
        $this->touchDir();
        $filename = $this->filepath . '/' . $this->fileName . '__' . $this->blobNum;
        move_uploaded_file($this->tmpPath, $filename);
    }
    //API返回数据
    public function apiReturn()
    {
        if ($this->blobNum == $this->totalBlobNum) {
            if (file_exists($this->filepath . '/' . $this->fileName)) {
                $data['code'] = 2;
                $data['msg'] = 'success';
                $data['file_full_name'] = str_replace(['./'], ['/'], $this->filepath.'/'.$this->fileName);
                $data['file_name'] = substr($this->fileName, 0, strrpos($this->fileName, '.'));
                $data['file_extension'] = substr(strrchr($this->fileName, '.'), 1);
            }
        } else {
            if (file_exists($this->filepath . '/' . $this->fileName)) {
                $data['code'] = 1;
                $data['msg'] = 'waiting';
                $data['file_path'] = '';
            }
        }
        header('Content-type: application/json');
        echo json_encode($data);
    }
    private function touchDir()
    {
        if (!file_exists($this->filepath)) {
            return mkdir($this->filepath);
        }
    }
}


相关文章

windows下安装redis php

安装redis,  https://www.jb51.net/article/218746.htm下载php redis扩展,https://pecl.php.net/package/red...

opencart paypal 体验账号测试支付

opencart paypal 体验账号测试支付

很多朋友在设置独立站后台Paypal收款时,经常看到Live和Sandbox这两个字眼。是否会产生疑惑:这是干什么的呢?其实这里的LIVE模式是正常付款环境下的付款模式,Sandbox就是我们所说的沙...

redis

进入CMD命令进入相应redis目录cd redisredis-server.exe redis.windows.conf...

phpqrcode生成二维码,并在底部加上图片

Vendor('phpqrcode.phpqrcode');$font = ROOT_PATH.'public/static/common/font/hgzb.ttf'...

yii2框架怎么写子查询

在yii中使用子查询的方法第一步,先创建一个子查询,可以是基于 yii\db\Query 创建,也可以基于Model。$subQuery = Order::find()->where(['...

fastadmin后台表单元素添加验证码

data-rule="required;length(3~50);sn"...

发表评论    

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。