页面展示效果(支持编辑,单选,多选)
![在这里插入图片描述](https://img-blog.csdnimg.cn/06c3e9a3da94405db1b9c81620e089f0.png#pic_center)
一、页面 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'
, size: 10240
, 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;
$("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);
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
{
[SugarTable("picmeta")]
public partial class picmeta
{
public picmeta()
{
}
[SugarColumn(IsPrimaryKey =true)]
public string filename { get; set; }
public string name { get; set; }
public string type { get; set; }
public string size { get; set; }
public string ext { get; set; }
public DateTime? createtime { get; set; }
public string desc { get; set; }
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
{
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,
});
}
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 图片管理
[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 == 0)
{
pictureTypes.AddRange(PicturesPage.PictureTypes.Select(t => new SelectListItem()
{
Text = t.Value,
Value = t.Key
}));
}
ViewData["pictureTypes"] = pictureTypes;
return View(model);
}
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));
}
[HttpPost]
public JsonResult SearchImages(string pictype, string keyword,
int page, int rows)
{
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);
}
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);
}
else
{
idx = name.LastIndexOf("/");
if(idx == -1)
{
return Json(JsonResponse.Fail("无法识别图片类别"), JsonRequestBehavior.AllowGet);
}
pictype = name.Substring(0,idx);
name = name.Substring(idx + 1);
}
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);
}
}
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++;
}
}
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();
}
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 异步扫面文件
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);
}
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 上传图片保存记录
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)
{
}
}
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