layui图片管理器

页面展示效果(支持编辑,单选,多选)

在这里插入图片描述

一、页面 pictures.cshtml

@model Web.Admin.Models.PicturesPage
@{ 
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>@(string.IsNullOrWhiteSpace(Model.title)?"图片管理器": Model.title)</title>
    <link href="/administration/scripts/fancybox/jquery.fancybox.css" rel="stylesheet">
    <link href="/administration/scripts/layui/css/layui.css" rel="stylesheet" type="text/css" />
    <style>
 
        #piclist{
            width:100%;
            overflow:scroll;
        }
 
        #pagerBottom{
            width:100%;
            text-align:right;
        }
        div.empty-data {
            margin: 0 auto;
            height: 100px;
            text-align:center;
            line-height: 100px;
            display: block;
        }
 
        div.cell-pic {
            width:calc(25% - 4px);
            display: inline-block;
            position:relative;
        }
 
            div.cell-pic:hover {
                box-shadow: 1px 0px 5px 0px #858585;
            }
 
        .cell-pic .pic-check, .cell-pic .pic-size, .cell-pic .pic-action {
            display: inline-block;
            position: absolute;
            top: 5px;
            z-index: 1;
            color: gray;
            font-size: 12px;
            line-height: 12px;
            padding: 2px;
        }
 
        .cell-pic .pic-check {
            left:4px;
            z-index:2;
        }
 
        .cell-pic .pic-size {
            left: 22px;
            background-color: lightpink;
        }
 
        .cell-pic .pic-action {
            right: 5px;
            top:3px;
            padding:4px;
            z-index: 2;
            cursor: pointer;
            background-color: black;
            color: white;
            display:none;
        }
 
        div.cell-pic:hover .pic-action {
            display: inline-block;
        }
 
        .pic-desc {
            color: gray;
            font-size: 12px;
        }
 
        .pic-desc-input{
            width:calc(100% - 14px);
            padding:4px 6px;
            outline:none;
            border:1px solid whitesmoke;
        }
 
        .pic-spec{
            
        }
 
        .pic-spec-item {
            border:2px solid whitesmoke;
            border-radius:17px;
            width:30px;
            height:30px;
            display:inline-block;
            line-height:30px;
            overflow:hidden;
        }
 
            .pic-spec-item img {
                width: calc(100% - 4px);
                height: calc(100% - 4px);
            }
 
        .pic-spec-item.active {
            border-color:red;
        }
 
        div.cell-pic > a {
            display: inline-block;
            text-align: center;
        }
 
        div.cell-pic .showimg {
            max-width: 100%;
        }
    </style>
</head>
<body>
    <div class="layui-row" id="pic-search">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">查询</div>
                <div class="layui-card-body">
                    <form class="layui-form">
                        <div class="layui-input-inline layui-col-md2">
                            <select name="pictype" id="pictype" lay-filter="pictype">
                                @foreach (SelectListItem item in ViewData["pictureTypes"] as List<SelectListItem>)
                                {
                                    <option value="@item.Value">@item.Text</option>
                                }
                            </select>
                        </div>
                        <div class="layui-input-inline layui-col-md6">
                            @Html.TextBoxFor(x => x.keyword, new { placeholder = "图片描述,多个关键字用空格分隔", @class = "layui-input" })
                        </div>
                        <div class="layui-input-inline layui-col-md3">
                            <button type="button" id="btnSearch" class="layui-btn">查询</button>
                            @if (Model.editable)
                            {
                                <button type="button" id="btnUpload" class="layui-btn">上传图片</button>
                            }
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div id="pic-list" style="margin:10px 10px 0px;">
        <div id="piclist"></div>
        <div id="pagerBottom"></div>
    </div>
    <script src="/administration/scripts/jquery.js"></script>
    <script src="/administration/scripts/layui/layui.js"></script>
    <script src="/components/jquery.nicescroll.min.js"></script>
    <script src="/administration/scripts/fancybox/jquery.fancybox.min.js"></script>
    <script>
        /*
         * 获取选择的图片,返回数组
         */
        function getSelectedImage() {
            return $.map($("input:@(Model.single?"radio":"checkbox"):checked"), function (o) {
                return $(o).closest(".cell-pic").find(".pic-spec-item.active img").attr("src");
            });
        }
 
        const pageSize = 16;
        function search() {
            _search(1);
        }
 
        function renderPager(t,p) {
            layui.laypage.render({
                elem: 'pagerBottom'
                , count: t
                , limit: pageSize
                , curr: p
                , jump: function (obj, first) {
                    if (!first) {
                        _search(obj.curr, obj.limit);
                    }
                }
            });
        }
 
        function _search(p, s) {
            if (!s) {
                s = pageSize;
            }
 
            let index = layui.layer.load();
            $.post("/admin/home/searchImages", {
                pictype: $("#pictype").val(),
                keyword: $("#keyword").val(),
                page: p,
                rows: s
            }, function (data) {
                layui.layer.close(index);
                if (data.success) {
                    renderPager(data.result.total, p);
                    layui.laytpl($("#piclistTpl").html()).render(data.result, function (html) {
                        $("#piclist").html(html);
                        resize();
                    });
                }
                else {
                    layui.layer.alert(data.message);
                }
            });
        }
 
        function selectImage(a) {
            if ($(a).hasClass("active")) {
                return;
            }
            $(a).parent().find(".pic-spec-item.active").removeClass("active");
            $(a).addClass("active");
        }
 
        layui.use(["form", "layer", "laypage", "laytpl","upload"], function () {
            search();
            @if(Model.editable)
            {
                <text>window.uploader = layui.upload.render({
                elem: '#btnUpload'
                , url: '/admin/tool/upload'
                //, auto: true
                //, accept: "images"
                //, exts: "jpg|png|gif|bmp|jpeg"
                , size: 10240//10M
                , number: 1
                , before: function (obj) {
                    layui.layer.load();
                    this.data = {
                        pictype: $("#pictype").val()
                    };
                }
                , done: function (res) {
                    layui.layer.closeAll("loading");
                    if (res.success) {
                        search(1);
                    }
                    else if (res.message) {
                        layui.layer.alert(res.message);
                    }
                }
            });</text>
            }
        });
 
        function resize() {
            let cw = $("#piclist").width();
            let bh = cw / 4 - 10;
            //.width(bw)
            $("div.cell-pic>a").width(bh).height(bh).css("line-height", bh + "px");
            $("div.cell-pic .showimg").css("max-height", bh + "px");
        }
 
        function formatFileSize(fileSize) {
            var arrUnit = ["B", "Kb", "Mb", "Gb", "Tb", "Pb"];
            var powerIndex = Math.log2(fileSize) / 10;
            powerIndex = Math.floor(powerIndex);
            // index should in the unit range!
            var len = arrUnit.length;
            powerIndex = powerIndex < len ? powerIndex : len - 1;
            var sizeFormatted = fileSize / Math.pow(2, powerIndex * 10)
            sizeFormatted = sizeFormatted.toFixed(2);
            return sizeFormatted + arrUnit[powerIndex];
        }
 
        function showPicSpecPath(item,idx, s) {
            if (idx == 0) {
                return item.filename;
            }
 
            let index = item.filename.indexOf("/source/");
            if (index > -1) {
                return "/upload/" + item.type + "/thumb" + s.width + "_" + s.height + "/" + item.name;
            }
            return item.filename;
        }
 
        $(function () {
            let listHeight = $(window).height() - $("#pic-search").height()-10;
            $("#pic-list").height(listHeight);
            $("#piclist").height(listHeight - 55);
            $("#btnSearch").click(search);
            window.onresize = resize;
            @if(Model.editable)
            {
                <text>
            $("#piclist").on("blur", ".pic-desc-input", function () {
                let v = $(this).val().trim(), ov = $(this).data("val").trim();
                if (v != ov) {
                    let that = this;
                    $.post("/admin/home/updateImageDesc",
                        {
                            filename: $(this).data("path"),
                            desc: v
                        }, function () {
                            $(that).data("val", v);
                        });
                }
            });
            $("#piclist").on("click", ".pic-action-del", function () {
                let filename = $(this).parent().data("path");
                layui.layer.confirm("确定要删除该图片吗?注:删除后无法恢复!", { icon: 3, title: '提示' }, function (index) {
                    $.get("/admin/home/DelImage?fileName=" + filename, function () {
                        layui.layer.close(index);
                        search(1);
                    });
                });
            });
            </text>
            }
        });
    </script>
    <script id="piclistTpl" type="text/html">
        {{#  layui.each(d.rows, function(index, item){ }}
        <div class="cell-pic">
            <div class="pic-check"><input name="chooseImage" type="@(Model.single?"radio":"checkbox")" value="{{ item.filename }}"/></div>
            <div class="pic-size">{{ item.size[0].width }}*{{ item.size[0].height }},{{ formatFileSize(item.length) }}</div>
            <a href="{{ item.filename }}" data-fancybox="{{ item.name }}">
                <img class="showimg" src="{{ item.filename }}" alt="{{ item.desc||"" }}" />
            </a>
            @if (Model.editable)
            {
                <div class="pic-action" data-path="{{ item.filename }}">
                    <div class="pic-action-del">删除</div>
                </div>
                <div class="pic-desc"><input class="pic-desc-input" data-path="{{ item.filename }}" data-val="{{ item.desc||"" }}" value="{{ item.desc||"" }}" type="text" maxlength="50" placeholder="输入描述,多个空格分隔" /></div>
            }
            else
            {
                <div class="pic-desc">{{ item.desc||"无描述" }}</div>
            }
            <div class="pic-spec">
                {{# layui.each(item.size, function(idx, s){ }}
                <a class="pic-spec-item {{ idx == 0?"active":""}}" onclick="selectImage(this)">
                    <img src="{{ showPicSpecPath(item,idx,s) }}" title="选择尺寸:{{ s.width }}*{{ s.height}}" alt="尺寸:{{ s.width }}*{{ s.height}}" />
                </a>
                {{# }); }}
            </div>
        </div>
        {{# }); }}
        {{#  if(d.rows.length === 0){ }}
        <div class="empty-data">没有数据</div>
        {{#  } }}
    </script>
</body>
</html>

二、sqlite数据表

CREATE TABLE "picmeta" (
  "filename" varchar(500) NOT NULL,
  "name" varchar(50) NOT NULL,
  "type" varchar(100) NOT NULL,
  "size" varchar(2000) NOT NULL,
  "ext" varchar(20) NOT NULL DEFAULT '',
  "createtime" datetime(8) NOT NULL,
  "desc" nvarchar(100),
  "length" integer NOT NULL DEFAULT 0,
  PRIMARY KEY ("filename")
);
 
CREATE INDEX "IDX_TYPE"
ON "picmeta" (
  "type"
);

三、模型类

using System;
using System.Linq;
using System.Text;
using SqlSugar;
 
namespace Web.Core.Model
{
    ///<summary>
    ///
    ///</summary>
    [SugarTable("picmeta")]
    public partial class picmeta
    {
        public picmeta()
        {
        }
 
        /// <summary>
        /// Desc:
        /// Default:
        /// Nullable:True
        /// </summary>
        [SugarColumn(IsPrimaryKey =true)]
        public string filename { get; set; }
 
        /// <summary>
        /// Desc:
        /// Default:
        /// Nullable:True
        /// </summary>           
        public string name { get; set; }
 
        /// <summary>
        /// Desc:
        /// Default:
        /// Nullable:True
        /// </summary>           
        public string type { get; set; }
 
        /// <summary>
        /// Desc:
        /// Default:
        /// Nullable:True
        /// </summary>           
        public string size { get; set; }
 
        /// <summary>
        /// Desc:
        /// Default:
        /// Nullable:True
        /// </summary>           
        public string ext { get; set; }
 
        /// <summary>
        /// Desc:
        /// Default:
        /// Nullable:True
        /// </summary>           
        public DateTime? createtime { get; set; }
 
        /// <summary>
        /// Desc:
        /// Default:
        /// Nullable:True
        /// </summary>           
        public string desc { get; set; }
 
        /// <summary>
        /// 文件大小(byte)
        /// </summary>
        public int? length { get; set; }
 
    }
}

四、数据库链接语句:

<connectionStrings>
   <add name="uploadImageMeta" connectionString="Data Source=|DataDirectory|\images.db;Pooling=true;FailIfMissing=false" providerName="2" />
</connectionStrings>

五、数据库访问:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SqlSugar;
 
 
namespace Web.Core
{
    public class DbContext
    {
 
        /// <summary>
        /// 创建数据库访问实例(使用特性获取列键信息,不是从数据库服务器)
        /// </summary>
        /// <param name="autoClose">
        /// 自动关闭:每次执行操作都会执行 connection.close,
        /// 否则:需要用using(var db=getInstance()) 或者db.Ado.Dispose()或者db.Ado.Close()进行释放
        /// </param>
        /// <returns></returns>
        public static SqlSugarClient CreateContext(string conStr,
            SqlSugar.DbType dbType,
            bool autoClose)
        {
            return new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = dbType,
                IsAutoCloseConnection = autoClose,
                InitKeyType = InitKeyType.Attribute,
            });
        }
 
        /// <summary>
        /// 根据数据库连接配置创建数据库访问实例
        /// </summary>
        /// <param name="connectionStringConfigName"></param>
        /// <param name="autoClose">是否自动关闭</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">连接配置名称不能为空</exception>
        /// <exception cref="System.ArgumentException">数据库类型(ProviderName)配置无效</exception>
        public static SqlSugarClient CreateContext(string connectionStringConfigName, bool autoClose)
        {
            if (string.IsNullOrEmpty(connectionStringConfigName))
                throw new ArgumentNullException(nameof(connectionStringConfigName), "数据库连接配置名称不能为空");
 
            var con = ConfigurationManager.ConnectionStrings[connectionStringConfigName];
            if (con == null)
                return null;
 
            int dbType = 0;
            if (!int.TryParse(con.ProviderName, out dbType) || !Enum.IsDefined(typeof(DbType), dbType))
            {
                throw new ArgumentException("ProviderName", "数据库类型配置无效:0MySql,1Server");
            }
 
            return CreateContext(con.ConnectionString, (DbType)dbType, autoClose);
        }
    }
}

六、Controller:

#region 图片管理
        /// <summary>
        /// 图片管理页面
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Pictures(string title = null,string types = null,
            string keywords = null,bool editable = true,bool single = false)
        {
            PicturesPage model = new PicturesPage() {
                title = title,
                types = types,
                keyword = keywords,
                editable = editable,
                single = single
            };
            List<SelectListItem> pictureTypes = new List<SelectListItem>();
            string[] typeList = null;
            if (!string.IsNullOrWhiteSpace(model.types))
            {
                typeList = model.types.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            }
 
            if (typeList != null && typeList.Length == 1 && PicturesPage.PictureTypes.ContainsKey(typeList[0]))
            {
                pictureTypes.Add(new SelectListItem() { Text = PicturesPage.PictureTypes[typeList[0]], Value = typeList[0] });
            }
            else if (typeList != null && typeList.Length > 1)
            {
                pictureTypes.AddRange(PicturesPage.PictureTypes.Where(t => typeList.Contains(t.Key)).Select(t => new SelectListItem()
                {
                    Text = t.Value,
                    Value = t.Key
                }));
 
                /*
                if(pictureTypes.Count>1)
                {
                    pictureTypes.Insert(0, new SelectListItem() { Text = "请选择", Value = "" });
                }
                */
            }
 
            if (pictureTypes.Count == 0)
            {
                //pictureTypes.Add(new SelectListItem() { Text = "请选择", Value = "" });
                pictureTypes.AddRange(PicturesPage.PictureTypes.Select(t => new SelectListItem()
                {
                    Text = t.Value,
                    Value = t.Key
                }));
            }
            ViewData["pictureTypes"] = pictureTypes;
            return View(model);
        }
 
        /// <summary>
        /// 更新图片描述
        /// </summary>
        /// <param name="filename">图片路径</param>
        /// <param name="desc">描述信息</param>
        public JsonResult UpdateImageDesc(string filename, string desc)
        {
            if (!string.IsNullOrEmpty(filename))
            {
                try
                {
                    using (SqlSugarClient db = DbContext.CreateContext("uploadImageMeta", false))
                    {
                        Core.Model.picmeta pic = db.Queryable<Core.Model.picmeta>().Where(p => p.filename == filename).First();
                        if (pic != null)
                        {
                            pic.desc = desc;
                            db.Updateable(pic).UpdateColumns("desc").ExecuteCommand();
                        }
                    }
                }
                catch(Exception ex)
                {
                    return Json(JsonResponse.Fail(ex.Message));
                }
            }
            return Json(JsonResponse.OK(null));
        }
 
        /// <summary>
        /// 搜索图片
        /// </summary>
        /// <param name="pictype">图片类型</param>
        /// <param name="keyword">关键字</param>
        /// <param name="page">页索引,从1开始</param>
        /// <param name="rows">分页大小,默认10</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SearchImages(string pictype, string keyword,
            int page, int rows)
        {
            //AyncScanTypeImages(pictype);
            JsonResponse<PagedResult<List<PictureInfo>>> data = new JsonResponse<PagedResult<List<PictureInfo>>>();
            data.result = new PagedResult<List<PictureInfo>>();
            data.result.rows = new List<PictureInfo>();
            if (!string.IsNullOrEmpty(pictype) && PicturesPage.PictureTypes.ContainsKey(pictype))
            {
                using (SqlSugarClient db = DbContext.CreateContext("uploadImageMeta", false))
                {
                    try
                    {
                        ISugarQueryable<Core.Model.picmeta> query = db.Queryable<Core.Model.picmeta>().Where(p => p.type == pictype);
                        if (!string.IsNullOrEmpty(keyword))
                        {
                            string[] ks = keyword.Split(CommonHelper.spaceSplitor, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string k in ks)
                            {
                                query = query.Where(p => p.desc.Contains(k));
                            }
                        }
 
                        query = query.OrderBy(p => p.createtime, OrderByType.Desc);
                        int total = 0;
                        data.result.rows = query.ToPageList(page, rows, ref total).Select(p => new PictureInfo() {
                            filename = p.filename,
                            name = p.name,
                            ext = p.ext,
                            type = pictype,
                            size = p.size.Split(',').Select(s => {
                                string[] ss = s.Split('*');
                                return new ImageSize()
                                {
                                    width = int.Parse(ss[0]),
                                    height = int.Parse(ss[1])
                                };
                            }).ToList(),
                            length = p.length,
                            desc = p.desc,
                            createtime = p.createtime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                        }).ToList();
                        data.result.total = total;
                    }
                    catch (Exception ex)
                    {
                        data.message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                    }
                }
            }
 
            data.success = string.IsNullOrEmpty(data.message);
            return Json(data);
        }
 
        /// <summary>
        /// 移除图片
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public JsonResult DelImage(string fileName)
        {
            string dir = "/upload/";
            string dirPath = IOHelper.GetMapPath(dir);
            string name = fileName;
            if (!name.StartsWith(dir))
            {
                return Json(JsonResponse.Fail("无法识别的路径"), JsonRequestBehavior.AllowGet);
            }
 
            name = name.Substring(dir.Length);
            string pictype = null;
            int idx = name.IndexOf("/source/");
            if (idx > -1)
            {
                pictype = name.Substring(0, idx);
                name = name.Substring(idx + 8);//"/source/".Length
            }
            else
            {
                idx = name.LastIndexOf("/");
                if(idx == -1)
                {
                    return Json(JsonResponse.Fail("无法识别图片类别"), JsonRequestBehavior.AllowGet);
                }
 
                pictype = name.Substring(0,idx);
                name = name.Substring(idx + 1);//"/".Length
            }
 
            if(string.IsNullOrEmpty(pictype))
            {
                return Json(JsonResponse.Fail("无法识别图片类别"), JsonRequestBehavior.AllowGet);
            }
 
            if (string.IsNullOrEmpty(name))
            {
                return Json(JsonResponse.Fail("不能清空图片类别目录"), JsonRequestBehavior.AllowGet);
            }
 
            try
            {
                string sdirPath = dirPath + pictype + "/";
                if (Directory.Exists(sdirPath))
                {
                    System.IO.File.Delete(sdirPath + name);
                    System.IO.File.Delete(sdirPath + "source/" + name);
                    Directory.GetDirectories(sdirPath, "thumb*_*").Select(d =>
                    {
                        System.IO.File.Delete(sdirPath + Path.GetFileName(d) + "/" + name);
                        return true;
                    });
                }
                using (SqlSugarClient db = DbContext.CreateContext("uploadImageMeta", false))
                {
                    db.Deleteable<Core.Model.picmeta>().Where(p => p.filename == fileName).ExecuteCommand();
                }
                return Json(JsonResponse.OK(null), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(JsonResponse.Fail(ex.InnerException == null ? ex.Message : ex.InnerException.Message), JsonRequestBehavior.AllowGet);
            }
        }
 
        /// <summary>
        /// 读取单个图片
        /// </summary>
        /// <param name="dir">根目录</param>
        /// <param name="dirPath">根目录绝对路径</param>
        /// <param name="db">数据库访问实例</param>
        /// <param name="list">列表</param>
        /// <param name="start">请求索引</param>
        /// <param name="end">请求截至</param>
        /// <param name="file">完整文件名</param>
        /// <param name="name">文件名称</param>
        /// <param name="fileName">文件网络虚拟路径</param>
        /// <param name="ext">文件后缀</param>
        /// <param name="pictype">图片类型</param>
        /// <param name="pic">图片元数据</param>
        /// <param name="dirs">规格目录</param>
        /// <param name="total">记录总数</param>
        private void ReadUploadImage(string dir,string dirPath,
            List<PictureInfo> list,
            SqlSugarClient db,
            string keyword,
            int start,int end,
            string file,string name,
            string fileName,string ext,
            string pictype,Core.Model.picmeta pic,
            IEnumerable<Tuple<string, int, int>> dirs,
            ref int total)
        {
            if (pic == null)
            {
                ImageInfo image = ImageHelper.GetInfo(file);
                if (image != null)
                {
                    bool invalidExt = ext.IndexOf("_")>-1;
                    if (invalidExt)
                    {
                        string rfile = file + ".jpg";
                        ext = ".jpg";
                        fileName += ext;
                        System.IO.File.Move(file, rfile);
                        file = rfile;
                    }
 
                    List<ImageSize> picSize = new List<ImageSize>() {
                        image.size
                    };
 
                    if (dirs != null)
                    {
                        picSize.AddRange(dirs.Where(d =>
                        {
                            string tfile = dirPath + d.Item1 + "/" + name;
                            bool exists = System.IO.File.Exists(tfile);
                            if (exists && invalidExt)
                            {
                                System.IO.File.Move(tfile, tfile + ext);
                            }
                            return exists;
                        }).Select(d => new ImageSize { width = d.Item2, height = d.Item3 }));
                    }
 
                    if (invalidExt)
                    {
                        name += ext;
                    }
 
                    pic = new Core.Model.picmeta()
                    {
                        filename = fileName,
                        name = name,
                        ext = ext,
                        type = pictype,
                        size = string.Join(",", picSize.Select(s => string.Format("{0}*{1}", s.width, s.height))),
                        length = Convert.ToInt32(new FileInfo(file).Length),
                        createtime = System.IO.File.GetLastWriteTime(file),
                    };
 
                    if (string.IsNullOrEmpty(keyword))
                    {
                        if (total >= start && total < end)
                        {
                            list.Add(new PictureInfo()
                            {
                                filename = fileName,
                                name = name,
                                ext = ext,
                                type = pictype,
                                size = picSize,
                                length = pic.length,
                                createtime = pic.createtime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                            });
                        }
                        total++;
                    }
 
                    db.Insertable(pic).ExecuteCommand();
                }
            }
            else if(ImageDescFilter(pic.desc,keyword))
            {
                if (total >= start && total < end)
                {
                    List<ImageSize> picSize = pic.size.Split(',').Select(s => {
                        string[] ss = s.Split('*');
                        return new ImageSize()
                        {
                            width = int.Parse(ss[0]),
                            height = int.Parse(ss[1])
                        };
                    }).ToList();
 
                    list.Add(new PictureInfo()
                    {
                        filename = fileName,
                        name = name,
                        ext = ext,
                        type = pictype,
                        size = picSize,
                        length = pic.length,
                        desc = pic.desc,
                        createtime = pic.createtime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    });
                }
                total++;
            }
        }
 
        /// <summary>
        /// 读取单个图片
        /// </summary>
        /// <param name="dir">根目录</param>
        /// <param name="dirPath">根目录绝对路径</param>
        /// <param name="db">数据库访问实例</param>
        /// <param name="file">完整文件名</param>
        /// <param name="name">文件名称</param>
        /// <param name="fileName">文件网络虚拟路径</param>
        /// <param name="ext">文件后缀</param>
        /// <param name="pictype">图片类型</param>
        /// <param name="dirs">规格目录</param>
        private void ReadUploadImage(string dirPath,
            SqlSugarClient db,
            string file, string name,
            string fileName, string ext, string pictype,
            IEnumerable<Tuple<string, int, int>> dirs)
        {
            ImageInfo image = ImageHelper.GetInfo(file);
            if (image == null)
            {
                return;
            }
 
            bool invalidExt = ext.IndexOf("_") > -1;
            if (invalidExt)
            {
                string rfile = file + ".jpg";
                ext = ".jpg";
                fileName += ext;
                System.IO.File.Move(file, rfile);
                file = rfile;
            }
 
            List<ImageSize> picSize = new List<ImageSize>() {
                image.size
            };
 
            if (dirs != null)
            {
                picSize.AddRange(dirs.Where(d =>
                {
                    string tfile = dirPath + d.Item1 + "/" + name;
                    bool exists = System.IO.File.Exists(tfile);
                    if (exists && invalidExt)
                    {
                        System.IO.File.Move(tfile, tfile + ext);
                    }
                    return exists;
                }).Select(d => new ImageSize { width = d.Item2, height = d.Item3 }));
            }
 
            if (invalidExt)
            {
                name += ext;
            }
 
            Core.Model.picmeta pic = new Core.Model.picmeta()
            {
                filename = fileName,
                name = name,
                ext = ext,
                type = pictype,
                size = string.Join(",", picSize.Select(s => string.Format("{0}*{1}", s.width, s.height))),
                length = Convert.ToInt32(new FileInfo(file).Length),
                createtime = System.IO.File.GetLastWriteTime(file),
            };
 
            db.Insertable(pic).ExecuteCommand();
        }
 
        /// <summary>
        /// 过滤关键字
        /// </summary>
        /// <param name="desc"></param>
        /// <param name="keyword"></param>
        /// <returns></returns>
        private bool ImageDescFilter(string desc,string keyword)
        {
            if(string.IsNullOrWhiteSpace(keyword))
            {
                return true;
            }
 
            if(string.IsNullOrWhiteSpace(desc))
            {
                return false;
            }
 
            string[] ks = keyword.Split(CommonHelper.spaceSplitor,StringSplitOptions.RemoveEmptyEntries);
            string[] ds = desc.Split(CommonHelper.spaceSplitor, StringSplitOptions.RemoveEmptyEntries);
            return ds.Intersect(ks).Count() == ks.Length;
        }
 
        #region 异步扫面文件
        /// <summary>
        /// 扫描类型图片
        /// </summary>
        /// <param name="pictype">图片类型</param>
        private void AyncScanTypeImages(string pictype)
        {
            if (string.IsNullOrEmpty(pictype) || !PicturesPage.PictureTypes.ContainsKey(pictype))
            {
                return;
            }
 
            string key = string.Format(CacheKeys.ScanTypeImage,pictype);
            if(BSPCache.Get(key) != null)
            {
                return;
            }
            Task.Factory.StartNew(ScanTypeImages, pictype);
        }
 
        /// <summary>
        /// 扫描类型图片
        /// </summary>
        /// <param name="state"></param>
        private void ScanTypeImages(object state)
        {
            string pictype = (string)state;
            string key = string.Format(CacheKeys.ScanTypeImage, state);
            try
            {
                string dir = "/upload/" + pictype + "/";
                string dirPath = IOHelper.GetMapPath(dir);
                if (!Directory.Exists(dirPath))
                {
                    return;
                }
                using (SqlSugarClient db = DbContext.CreateContext("uploadImageMeta", false))
                {
                    //多规格
                    string sdir = dir + "source/";
                    string sdirPath = dirPath + "source/";
 
                    IEnumerable<Tuple<string, int, int>> dirs = null;
                    if (Directory.Exists(sdirPath))
                    {
                        dirs = Directory.GetDirectories(dirPath, "thumb*_*").Select(d =>
                        {
                            string spec = Path.GetFileName(d);
                            string[] ss = spec.Substring(5).Split('_');
                            return Tuple.Create(spec, int.Parse(ss[0]), int.Parse(ss[1]));
                        });
 
                        foreach (string file in Directory.EnumerateFiles(sdirPath))
                        {
                            string ext = Path.GetExtension(file);
                            string name = Path.GetFileName(file);
                            string fileName = sdir + name;
                            Core.Model.picmeta pic = db.Queryable<Core.Model.picmeta>().Where(f => f.filename == fileName).First();
                            if (pic == null)
                            {
                                ReadUploadImage(dirPath, db, file, name, fileName, ext, pictype, dirs);
                            }
                        }
                    }
 
                    foreach (string file in Directory.EnumerateFiles(dirPath))
                    {
                        string name = Path.GetFileName(file);
                        string fileName = dirPath + "source/" + name;
                        //多格式过滤
                        if (System.IO.File.Exists(fileName))
                        {
                            continue;
                        }
                        string ext = Path.GetExtension(file);
                        fileName = dir + name;
                        Core.Model.picmeta pic = db.Queryable<Core.Model.picmeta>().Where(f => f.filename == fileName).First();
                        if (pic == null)
                        {
                            ReadUploadImage(dirPath, db, file, name, fileName, ext, pictype, null);
                        }
                    }
                }
            }
            finally
            {
                BSPCache.Remove(key);
            }
        }
        #endregion
        #endregion

七、上传保存文件信息:

#region 上传图片保存记录
        /// <summary>
        /// 插入上传的图片记录
        /// </summary>
        public static void InsertUploadImage(string pictype,string name)
        {
            if(string.IsNullOrEmpty(pictype) || string.IsNullOrEmpty(name))
            {
                return;
            }
 
            string dir = "/upload/" + pictype + "/";
            string dirPath = IOHelper.GetMapPath(dir);
            if (!Directory.Exists(dirPath))
            {
                return;
            }
 
            try
            {
                using (SqlSugarClient db = DbContext.CreateContext("uploadImageMeta", false))
                {
                    //多规格
                    string sdir = dir + "source/";
                    string sdirPath = dirPath + "source/";
                    string file = sdirPath + name;
                    if (File.Exists(file))
                    {
                        IEnumerable<Tuple<string, int, int>> dirs = null;
                        if (Directory.Exists(sdirPath))
                        {
                            dirs = Directory.GetDirectories(dirPath, "thumb*_*").Select(d =>
                            {
                                string spec = Path.GetFileName(d);
                                string[] ss = spec.Substring(5).Split('_');
                                return Tuple.Create(spec, int.Parse(ss[0]), int.Parse(ss[1]));
                            });
 
                            string ext = Path.GetExtension(file);
                            string fileName = sdir + name;
                            Core.Model.picmeta pic = db.Queryable<Core.Model.picmeta>().Where(f => f.filename == fileName).First();
                            if (pic == null)
                            {
                                ReadUploadImage(dirPath, db, file, name, fileName, ext, pictype, dirs);
                            }
                        }
                    }
                    else if(File.Exists(file = dirPath + name))
                    {
                        string ext = Path.GetExtension(file);
                        string fileName = dir + name;
                        Core.Model.picmeta pic = db.Queryable<Core.Model.picmeta>().Where(f => f.filename == fileName).First();
                        if (pic == null)
                        {
                            ReadUploadImage(dirPath, db, file, name, fileName, ext, pictype, null);
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                //插入失败
            }
        }
 
        /// <summary>
        /// 读取单个图片
        /// </summary>
        /// <param name="dir">根目录</param>
        /// <param name="dirPath">根目录绝对路径</param>
        /// <param name="db">数据库访问实例</param>
        /// <param name="file">完整文件名</param>
        /// <param name="name">文件名称</param>
        /// <param name="fileName">文件网络虚拟路径</param>
        /// <param name="ext">文件后缀</param>
        /// <param name="pictype">图片类型</param>
        /// <param name="dirs">规格目录</param>
        private static void ReadUploadImage(string dirPath,
            SqlSugarClient db,
            string file, string name,
            string fileName, string ext, string pictype,
            IEnumerable<Tuple<string, int, int>> dirs)
        {
            ImageInfo image = ImageHelper.GetInfo(file);
            if (image == null)
            {
                return;
            }
 
            bool invalidExt = ext.IndexOf("_") > -1;
            if (invalidExt)
            {
                string rfile = file + ".jpg";
                ext = ".jpg";
                fileName += ext;
                System.IO.File.Move(file, rfile);
                file = rfile;
            }
 
            List<ImageSize> picSize = new List<ImageSize>() {
                image.size
            };
 
            if (dirs != null)
            {
                picSize.AddRange(dirs.Where(d =>
                {
                    string tfile = dirPath + d.Item1 + "/" + name;
                    bool exists = System.IO.File.Exists(tfile);
                    if (exists && invalidExt)
                    {
                        System.IO.File.Move(tfile, tfile + ext);
                    }
                    return exists;
                }).Select(d => new ImageSize { width = d.Item2, height = d.Item3 }));
            }
 
            if (invalidExt)
            {
                name += ext;
            }
 
            Core.Model.picmeta pic = new Core.Model.picmeta()
            {
                filename = fileName,
                name = name,
                ext = ext,
                type = pictype,
                size = string.Join(",", picSize.Select(s => string.Format("{0}*{1}", s.width, s.height))),
                length = Convert.ToInt32(new FileInfo(file).Length),
                createtime = System.IO.File.GetLastWriteTime(file),
            };
 
            db.Insertable(pic).ExecuteCommand();
        }
        #endregion
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值