layui中的上传文件 照片,视频,文件

先上效果图

在这里就不给大家演示地址了,简单介绍一下,可以打开视频观看,打开图片,excel 可以点击下载  pdf在线预览,可删除

 

前端部分------------------------
//html
<div class="content"></div>



//js代码↓↓↓↓↓↓↓↓↓↓↓↓↓↓
layui.use(['layer','findFile'], function () { const $ = layui.$,//jquery layer = layui.layer,//弹出层 const findFile = layui.findFile; let paramUrl = location.search.substr(1, location.search.length - 1); findFile.render({ elem: 'content',//追加元素位置 url: 'queryByCond' + location.search,//文件请求地址方法 param: url2Object(paramUrl), saveUrl: 'upload' + location.search,//调用后台upload+项目路径方法 insertable: true,//是否有上传功能 deletable: true,//是否有删除功能 }) }); function url2Object(str) { let strContainer = {}; let arrStr = str.split("&") arrStr.forEach((item, index, arr) => { let arrA = item.split("=") strContainer[arrA[0]] = arrA[1] }) return strContainer }

 

处理上传文件的js文件在哪儿呢 我们layui引入的依赖性中对应到本地目录也就是在static目录下  static/js/lay-module

第一步在lay-config中添加新的依赖项   static/js/lay-config

 在static/js/lay-module添加 findFile目录  创建 findFile.js

内容如下

layui.define(["layer"], function (exports) {
    const layer = layui.layer,
        $ = layui.$,
        upload = layui.upload;
    let loading = null;
    let dataList = [];
    //被追加元素

    var findFile = {
        render: function (option) {
            if (option.elem) {
                option.elem = $('.' + option.elem) || $('#' + option.elem);
            } else {
                option.elem = ''
            }
            check(option)
            //被追加元素  按钮
            option.parentDiv = $('.fixedBtn');
            if (option.insertable) {
                uploadRender(option);
            }
        },
    }

    //检查属性
    function check(demo) {
        if (demo.elem.length >= 1) {
                create(demo);
        } else {
            layer.msg('请绑定载入元素ID');
            return false;
        }
        if (demo.url.length >= 1) {
            doquerydata(demo)
        } else {
            layer.msg('请求失败,未绑定请求地址');
            return false;
        }
    }

    //创建页面元素
    function create(demo) {
        if (demo.insertable) {
            $(demo.elem).append('<div class="layui-upload" id="fileList">\n' +
                '        <div class="fixedBtn">\n' +
                '            <button type="button" class="layui-btn-upload" id="upload">\n' +
                '                <i class="layui-icon">&#xe654;</i>\n' +
                '                <br>上传文件\n' +
                '            </button>\n' +
                '            <div class="clearfloat"></div>\n' +
                '        </div>\n' +
                '    </div>')
        } else {
            $(demo.elem).append('<div className="layui-upload" id="fileList">\n' +
                '              <div class="fixedBtn"></div>\n' +
                '           </div>')
        }

    }

    //请求数据添加到页面中
    function doquerydata(demo) {
        $.post(demo.url, demo.param, function (result) {
            dataList = result.data;
            dataList.forEach(function (item, key) {
                let itemType = item.fileUrl.substr(item.fileUrl.lastIndexOf('.') + 1, item.fileUrl.length);
                decideCreateElement(demo, item, key, itemType)
            })
        })
    }

    //添加不同类型的元素
    function decideCreateElement(demo, item, key, fileType) {
        const ShowImgPath = '../../file/';//图片上传后保存的位置
        const StaticImgPath = '../../static/images/thumb/';//静态图片相对路径
        // 如果是图片
        if (fileType == 'image' || fileType == 'jpeg' || fileType == 'jpg' || fileType == 'png' || fileType == 'gif' || fileType == 'bmp') {
            appenchild(demo, ShowImgPath, item, key, null, false, false)
            deletefunction('#fileList', key,demo)
            //放大图片
            imgShow(demo, '.showImg', ShowImgPath, item, key, false)
        } else if (fileType == 'xls' || fileType == 'xlsx' || fileType == 'doc' || fileType == 'docx' || fileType == 'ppt' || fileType == 'pptx' || fileType == 'txt' || fileType == 'pdf' || fileType == 'other') {//如果是excel
            if (fileType == 'xls') {//xls
                appenchild(demo, StaticImgPath, item, key, '' + fileType + '', false, false)
            } else if (fileType == 'xlsx') {//xlsx
                appenchild(demo, StaticImgPath, item, key, '' + fileType + '', false, false)
            } else if (fileType == 'doc') {//doc
                appenchild(demo, StaticImgPath, item, key, '' + fileType + '', false, false)
            } else if (fileType == 'docx') {//docx
                appenchild(demo, StaticImgPath, item, key, '' + fileType + '', false, false)
            } else if (fileType == 'ppt') {//ppt
                appenchild(demo, StaticImgPath, item, key, '' + fileType + '', false, false)
            } else if (fileType == 'pptx') {//pptx
                appenchild(demo, StaticImgPath, item, key, '' + fileType + '', false, false)
            } else if (fileType == 'txt') {//txt
                appenchild(demo, StaticImgPath, item, key, '' + fileType + '', false, false)
            } else if (fileType == 'pdf') {
                appenchild(demo, StaticImgPath, item, key, '' + fileType + '', false, false)
            } else {//其他
                appenchild(demo, StaticImgPath, item, key, '' + fileType + '', false, false)
            }
            deletefunction('#fileList', key,demo)
        } else if (fileType == 'mp4') {
            appenchild(demo, ShowImgPath, item, key, null, true, false)
            deletefunction('#fileList', key,demo)
            //放大图片
            imgShow(demo, '.showImg', ShowImgPath, item, key, true)
        } else {
            appenchild(demo, StaticImgPath, item, key, 'other', false, true)
            deletefunction('#fileList', key,demo)
        }
    }

    //添加元素
    function appenchild(demo, ImgPath, item, key, format, videoControl, isother) {
        //参数: 图片引入路径(图片保存后路径/静态路径) item 当前元素 当前元素对应的索引  用于引入静态图片 文件后缀 是否属于视频 是否属于其他文件
        if (demo.deletable) {//是否拥有删除功能
            if (videoControl) {//是否是视频
                if (demo.insertable) {
                    demo.parentDiv.before('<div class="box" style="width: 100px"><video src="' + ImgPath + item.fileUrl + '" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"></video><button class="DBtn clear' + key + '" id=' + item.fileId + ' name="' + item.fileUrl + '">x</button><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                } else {
                    demo.parentDiv.before('<div class="box" style="width: 100px"><video src="' + ImgPath + item.fileUrl + '" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"></video><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                }
            } else {
                if (!format) {//如果是用图片保存后的路径 需要添加图片点击放大
                    if (demo.insertable) {
                        demo.parentDiv.before('<div class="box" style="width: 100px"><img src="' + ImgPath + item.fileUrl + '" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"><button class="DBtn clear' + key + '" id=' + item.fileId + ' name="' + item.fileUrl + '">x</button><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                    } else {
                        demo.parentDiv.before('<div class="box" style="width: 100px"><img src="' + ImgPath + item.fileUrl + '" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                    }

                } else {//静态图片路径
                    if (format == 'pdf') {
                        if (demo.insertable) {
                            demo.parentDiv.before('<div class="box" style="width: 100px"><a href="../../file/' + item.fileUrl + '" target="_blank"><img src="' + ImgPath + format + '.png" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"></a><button class="DBtn clear' + key + '" id=' + item.fileId + ' name="' + item.fileUrl + '">x</button><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                        } else {
                            demo.parentDiv.before('<div class="box" style="width: 100px"><a href="../../file/' + item.fileUrl + '" target="_blank"><img src="' + ImgPath + format + '.png" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"></a><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                        }

                    } else {
                        if (isother) {
                            if (demo.insertable) {
                                demo.parentDiv.before('<div class="box" style="width: 100px"><a href="../../file/' + item.fileUrl + '" download="' + item.fileName + '"><img src="' + ImgPath + format + '.png" alt="' + item.fileName + '" class="layui-upload-img' + key + '"></a><button class="DBtn clear' + key + '" id=' + item.fileId + ' name="' + item.fileUrl + '">x</button><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                            } else {
                                demo.parentDiv.before('<div class="box" style="width: 100px"><a href="../../file/' + item.fileUrl + '" download="' + item.fileName + '"><img src="' + ImgPath + format + '.png" alt="' + item.fileName + '" class="layui-upload-img' + key + '"></a><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                            }
                        } else {
                            if (demo.insertable) {
                                demo.parentDiv.before('<div class="box" style="width: 100px"><a href="../../file/' + item.fileUrl + '" download="' + item.fileName + '"><img src="' + ImgPath + format + '.png" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"></a><button class="DBtn clear' + key + '" id=' + item.fileId + ' name="' + item.fileUrl + '">x</button><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                            } else {
                                demo.parentDiv.before('<div class="box" style="width: 100px"><a href="../../file/' + item.fileUrl + '" download="' + item.fileName + '"><img src="' + ImgPath + format + '.png" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"></a><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                            }

                        }

                    }
                }
            }
        } else {
            if (videoControl) {
                demo.parentDiv.before('<div class="box" style="width: 100px"><video src="' + ImgPath + item.fileUrl + '" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"></video><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
            } else {
                if (!format) {//如果是用图片保存后的路径 需要添加图片点击放大
                    demo.parentDiv.before('<div class="box" style="width: 100px"><img src="' + ImgPath + item.fileUrl + '" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                } else {//静态图片路径
                    if (format == 'pdf') {
                        demo.parentDiv.before('<div class="box" style="width: 100px"><a href="../../file/' + item.fileUrl + '" target="_blank"><img src="' + ImgPath + format + '.png" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"></a><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                    } else {
                        if (isother) {
                            if (demo.insertable) {
                                demo.parentDiv.before('<div class="box" style="width: 100px"><a href="../../file/' + item.fileUrl + '" download="' + item.fileName + '"><img src="' + ImgPath + format + '.png" alt="' + item.fileName + '" class="layui-upload-img' + key + '"></a><button class="DBtn clear' + key + '" id=' + item.fileId + ' name="' + item.fileUrl + '">x</button><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                            } else {
                                demo.parentDiv.before('<div class="box" style="width: 100px"><a href="../../file/' + item.fileUrl + '" download="' + item.fileName + '"><img src="' + ImgPath + format + '.png" alt="' + item.fileName + '" class="layui-upload-img' + key + '"></a><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                            }
                        } else {
                            demo.parentDiv.before('<div class="box" style="width: 100px"><a href="../../file/' + item.fileUrl + '" download="' + item.fileName + '"><img src="' + ImgPath + format + '.png" alt="' + item.fileName + '" class="layui-upload-img showImg' + key + '"></a><p class="title" title=' + item.fileName + '>' + item.fileName + '</p></div>');
                        }
                    }
                }
            }
        }
    }

    //上传功能的实现
    function uploadRender(demo) {
        upload.render({
            elem: '#upload'
            , url: demo.saveUrl
            , multiple: true
            , accept: 'file'
            , size: 100 * 1024
            , before: function (obj) {
                loading = layer.load(1);
            }
            , done: function (res) {//上传完毕
                layer.close(loading)
                if (res.code == 0) {
                    layer.msg('上传附件' + res.msg, {
                        time: 1500,
                        icon: 1
                    })
                    $('#fileList div[class=box]').remove();//清空dom
                    dataList.push(res.data);//添加记录
                    dataList.forEach(function (item, key) {//再次render
                        let itemType = item.fileUrl.substr(item.fileUrl.lastIndexOf('.') + 1, item.fileUrl.length);
                        decideCreateElement(demo, item, key, itemType)
                    })
                    const data=demo.param.data;
                    const height=demo.param.height;
                    const currentLine=demo.param.currentLine;
                    demo.reloadFn(data,height,currentLine);
                } else {
                    layer.msg(res.msg, {
                        time: 2000,
                        icon: 5
                    })
                }
            }, error: function (res) {
                layer.close(loading)
            }
        });
    }

    //删除
    function deletefunction(dom, key,option) {
        const deleteModalName=option.deletable;
        //参数 dom:要从那个元素中删除  key:元素对应的动态key值
        $('.clear' + key).bind('click', function () {//删除指定预上传图片
            let fileId = $(this).attr('id')//每张图片对应的id

            delete $('' + dom + '')[key];//删除指定图片
            delete dataList[key];
            $(this.parentNode).remove();//删除页面元素
            const postUrl=deleteModalName?`${deleteModalName}`:'deleteById';
            $.post(postUrl, {fileId: fileId}, function (res) {//删除数据库中对应的数据
                if (res.code == 0) {
                    const data=option.param.data;
                    const height=option.param.height;
                    const currentLine=option.param.currentLine;
                    option.reloadFn(data,height,currentLine);
                    layer.msg(res.msg, {
                        time: 1500,
                        icon: 1
                    })
                }
            })
        })
    }

    //放大图片和视频
    function imgShow(demo, ShowClassName, ShowImgPath, item, key, videoControl) {
        //对应图片放大预览
        $("" + ShowClassName + "" + key).bind('click', function () {
            var width = $("" + ShowClassName + "" + key).width();
            var height = $("" + ShowClassName + "" + key).height();
            var scaleWH = width / height;
            var bigH = 750;
            var bigW = scaleWH * bigH;
            if (bigW > 1200) {
                bigW = 1200;
                bigH = bigW / scaleWH;
            }

            if (!videoControl) {
                // 放大预览图片
                parent.window.layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 1,
                    shadeClose: true,
                    area: [bigW + 'px', bigH + 'px'], //宽高
                    content: "<img width='" + bigW + "' height='" + bigH + "' src=" + ShowImgPath + item.fileUrl + ">"
                });
            } else {
                // 放大预览图片
                parent.window.layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 1,
                    scroll: false,
                    shadeClose: true,
                    area: [bigW + 'px', bigH + 'px'], //宽高
                    content: "<video  controls autoplay width='" + bigW + "' height='" + bigH + "' src=" + ShowImgPath + item.fileUrl + "></video>",
                    success: function (layero, index) {
                        $(layero[0].firstChild).css('overflow', 'hidden')//去除视频页侧边滚动条
                    }
                });
            }

        });
    }

    exports("findFile", findFile);
})
View Code

配置好后台接口就ok了

 

 

后端部分------------------------

  

 

 

 插件内置调用controller方法

后端写好controller层和model层后台代码即可

开始展示 实例代码---请根据自己项目需求编写

<?php
namespace Mt\Controller;

use Mt\Controller\m\FileController_m;

class FileController extends FileController_m
{
    public function __construct()
    {
        parent::__construct();
    }

    public function upload()
    {
        try {
            $result = D('Mt/File')->upload($_GET[assetId], $_GET[assetType]);
            $this->ajaxReturnEx(0, '成功', $result);
        } catch (\Exception $e) {
            $this->ajaxReturnEx(1, $e->getMessage());
        }
    }

}
controller层代码

 

<?php

namespace Mt\Controller\m;

use Index\Controller\BaseController;

class FileController_m extends BaseController
{
    public function __construct()
    {
        parent::__construct();
    }
    //List page
    public function index()
    {
        $this->assign('title', '路面附件');
        $this->display('File/index');
    }
}
controller_m层代码

 

<?php

namespace Mt\Model;

use Mt\Model\m\FileModel_m;
use Think\Exception;

class FileModel extends FileModel_m
{
    public function __construct()
    {
        parent::__construct();
    }

    public function upload($assetId, $assetType)
    {
        $upload = new \Think\Upload(C("upload"));// 实例化上传类
        $info = $upload->uploadOne($_FILES['file']);
        if (!$info) {// 上传错误提示错误信息
            //$this->error($upload->getError());
            throw new Exception($upload->getError());
        } else {// 上传成功 获取上传文件信息
            $fileUrl = $info['savepath'] . $info['savename'];
            $vo = [assetId => $assetId, assetType => $assetType, fileUrl => $fileUrl, fileName => $info['name']];
            $this->saveAdd($vo);
            return $vo;
        }
    }
}
Model层代码

 

 

 
 
posted @ 2022-09-14 10:27  火知火味  阅读(630)  评论(0编辑  收藏  举报