php + layui 文件上传 以及 拖拽上传

HTML:
  
                <div id="box">
                    <div id="drop_area">将文件拖拽到此区域</div>
                    <div id="area_img"> <img src="../images/tzsc.png" id="img_upfiles"  style="cursor: pointer"/> </div>
                </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <div class="layui-upload" style="margin-left: 730px">
                <button type="button" class="layui-btn layui-btn-normal" id="upfiles">&emsp;<i class="layui-icon"></i> 文件上传&emsp;</button>
                <span style="color: #666"></span>
            </div>
            <table id="tabl1" class="layui-table" style="width: 850px;margin-top: -38px;margin-left: -110px;">
                <colgroup>
                    <col width="300"><col width="80"><col width="160"><col width="300">
                </colgroup>
                <thead>
                <tr>
                    <th>文件名称</th><th>类型</th><th>操作</th><th>备注</th>
                </tr>
                </thead>
                <tbody id="fileList"></tbody>
            </table>
        </div>
    </div>

 

JS:

XMLhttpReuest.js
function ajaxFunction()
{
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            try
            {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e)
            {
                alert("您的浏览器不支持AJAX!");
                return false;
            }
        }
    }
    return xmlHttp;
}
{?*拖拽上传*?}
<script>
    window.onload = function () {
        var box = document.getElementById('box');
        box.ondragenter = function (e) {
            e.preventDefault();
        }
        box.ondragover = function (e) {
            e.preventDefault();
        }
        box.ondragleave = function (e) {
            e.preventDefault();
        }
        box.ondrop = function (e) {
            e.preventDefault();
            var file = e.dataTransfer.files[0];
            var formData = new FormData();
            formData.append('file', file);

            var xml = ajaxFunction();
            xml.open("post", './ajax.files.upload.php?MID={?$lev.MID?}&upfilecode={?$upfilecode?}&path=djyp_file', true);
            xml.send(formData);
            xml.onreadystatechange = function () {
                console.log(xml.readyState);
                console.log(xml.status);
                if(xml.readyState == 4 && xml.status==200){
                    var res=JSON.parse(xml.responseText);
                    if(res.code > 0){
                        layer.msg(res.msg);
                    }else {
                        var tr = $(['<tr>'
                            , ' <td><input type="text" autocomplete="off" placeholder="请输入文件名称" value="' + res.old_name + '" name="old_name[' + res.id + ']"></td>'
                            , '<td>' + res.file_ext + '</td>'
                            , '<td>'
                            , '<a class="layui-btn layui-btn-warm layui-btn-xs fileread" href="' + res.path + res.new_name +'.'+ res.file_ext + '" target="_blank"> <i class="layui-icon layui-icon-read"></i>查看 </a>'
                            , '<button type="button" class="layui-btn layui-btn-xs filedel" style="background: #ff5722;"> <i class="layui-icon layui-icon-delete"></i>删除 </button>'
                            , '</td>'
                            , ' <td><input type="text" autocomplete="off" placeholder="请输入备注"  name="old_name1[' + res.id + ']"></td>'
                            , '</tr>'].join(''));
                        //删除
                        tr.find('.filedel').on('click', function () {
                            $.post('ajax.attach.file.del.php?MID={?$lev.MID?}',{id:res.id},function(data){
                                if (data.code > 0)
                                    parent.layer.msg(data.msg, {offset: '0px', icon: 2, time: 1000});
                                else
                                    tr.remove();
                            });

                        });
                        $("#fileList").append(tr);

                        var title = $("#title");
                        if(title.val() == '')
                            title.val(res.old_name);
                    }
                }
            }
        }
    }
</script>

php:

ajax.files.upload.php
header("Content-Type:text/html;charset=UTF-8");$CODE = $_GET['upfilecode'];
$PATH = $_GET['path'];


$a = new UPFILE($CODE, $PATH, $_FILES['file'], $pl);


class UPFILE
{
    public $pl = '';
    public $file = '';

    public function __construct($code, $path, $file, $pl)
    {
        if ($code == '')
            $this->ExtFrm(1, "缺少上传编码");
        if ($path == '')
            $this->ExtFrm(2, "缺少上传路径");
        if (!$file)
            $this->ExtFrm(3, "找不到上传文件");
        if ($file['size'] > 1024 * 1024 * 50) {
            $this->ExtFrm(3, "上传失败,文件大小超过限制(文件大小:50MB)");
        }
        $size=round($file['size']/1024/1024, 2);
        $this->pl = $pl;
        $this->file = $file;
        $this->type = $path;

        $filePath = $this->createFile($path);
        $fileOld = $this->verifyFile();
        $this->fileupload($code, $filePath, $fileOld,$size);
    }

    /**
     * Method:createFile
     * Desc:创建文件路径
     */
    public function createFile($path)
    {
        $Ym = date('Ym');
        $filepath = $Ym . ($path != "" ? "/" : "") . $path;
        $fullpath = '../upfiles/' . $filepath;
        if (!is_dir($fullpath)) {
            $res = mkdir($fullpath, 0777, true);
        }
        return array($filepath . "/", $fullpath . "/");
    }

    /**
     * Method:verifyFile
     * Desc:验证文件格式
     */
    public function verifyFile()
    {
        $pinfo = pathinfo($this->file["name"]);
        $extension = strtolower($pinfo['extension']);
        switch ($this->type) {
            case 'message_img': //消息推送 - 富文本 图片上传
                $file_format = array("jpg", "jpeg", "gif", "png");
                if (!in_array($extension, $file_format)) {
                    $this->ExtFrm(4, "上传失败,文件格式不正确(支持:jpg,gif,png)");
                }
                break;
            default:
                $file_format = array("jpg", "jpeg", "gif", "png", "rar", "zip", "doc", "docx", "xls", "xlsx", "pdf", "txt", "ppt", "pptx", "tif",'mp4');
                if (!in_array($extension, $file_format)) {
                    $this->ExtFrm(4, "上传失败,文件格式不正确(支持:jpg,gif,png,rar,zip,doc,docx,xls,xlsx,pdf,txt,ppt,pptx,tif,mp4)");
                }
                break;
        }
        return array("filename" => $pinfo['filename'], "extension" => $extension);
    }

    /**
     * Method:fileupload
     * Desc:上传文件
     */
    public function fileupload($code, $filepath, $fileold,$size)
    {
        $old_name = $fileold['filename'];
        $new_name = time() . rand(0, 500000) . dechex(rand(0, 10000));
        move_uploaded_file($this->file['tmp_name'], $filepath[1] . $new_name . "." . $fileold['extension']);

        if ($this->type != 'message_img') {
            $sql = "insert into system_attach (`BM`,`YFJMC`,`XFJMC`,`WJLJ`,`WJLX`,`CJSJ`,`CJRID`,`CJRMC`,`SIZE`) values (:BM,:YFJMC,:XFJMC,:WJLJ,:WJLX,:CJSJ,:CJRID,:CJRMC,:SIZE)";
            $this->pl->query($qry, $sql, array(
                ":BM" => $code,
                ":YFJMC" => $old_name . ".",
                ":XFJMC" => $new_name . "." . $fileold['extension'],
                ":WJLJ" => $filepath[0],
                ":WJLX" => $fileold['extension'],
                ":CJSJ" => date("Y-m-d H:i:s"),
                ":CJRID" => $_SESSION['UID'],
                ":CJRMC" => $_SESSION['NAME'],
                ":SIZE" => $size,
            ));
            $id = $this->pl->insert_id();
        }
        $this->ExtFrm(0, "上传成功", $id, $filepath[1], $new_name, $old_name, $fileold['extension']);
    }

    /**
     * Method:extFrm
     * Desc:结果返回
     */
    public function extFrm($code, $msg, $id = 0, $filepath = "", $new_name = '', $old_name = '', $file_ext = "")
    {
        if ($code > 0) {
            $ExtFrm = array("code" => $code, "msg" => $msg);
        } else if ($this->type == 'message_img') {
            $title = $new_name . "." . $file_ext;
            $ExtFrm = array("code" => $code, "msg" => $msg, "data" => array("src" => $filepath . $title, "title" => $title));
        } else {
            $ExtFrm = array("code" => $code, "msg" => $msg, "id" => $id, "path" => $filepath, "new_name" => $new_name, "old_name" => $old_name, "file_ext" => $file_ext);
        }
        exit(json_encode($ExtFrm));
    }
}

?>

 

上一篇:Layui 项目前端导出Excel文件总结(两种方式)


下一篇:layui 日期渲染