开发框架:MVC,Layui
列表主界面这里就不展示了,可以去看看这篇文章:Layui项目实战,这里讲的是“上传Banner”界面功能:
其中包括,多文件上传,预览,后台接收,保存,仅此而已
1.前端Html代码
head头部代码块:
注意:这里引用的是Layui和jQuery插件,不过重点功能还是在jQuery,Layui只是起到样式效果
PushCircleBanner
body代码块:
注意:这里既然是文件上传,重点自然是input[“file”],multiple=“multiple"多文件上传,accept=”.png,.jpg,.jpeg,.bmp,.gif,.jfif,.ico "限制允许选择的文件类型
性别:
是否去重:
图片上传:
Js代码块:
注意:PushFiles方法,由点击显示的上传按钮,再触发隐藏的input[“file”]按钮的点击方法,改变files值后触发该方法,实现多文件上传效果,也是这里前端界面展示的重点
2.后台C#代码
注意:下面的后台代码块,只要把间隔的注意提示去掉,就能拼接出完整的后台代码
///
/// 图片批量上传
///
///
public ActionResult PushBanner()
{
后台登录校验
if (!(Session["account"] is AccountModel account))
return Json(new { code = -1, msg = "登录异常" }, JsonRequestBehavior.AllowGet);
获取前端传输参数:
StringBuilder msg = new StringBuilder();
int error = 0;
AliyunOssProvider aliyunOss = new AliyunOssProvider();
string suffix = string.Empty;
var files = Request.Files; //ajax传输文件
var sex = Request.Form["sex"] == null ? 0 : int.Parse(Request.Form["sex"]);
var isDistinct = Request.Form["isDistinct"] == null ? 0 : int.Parse(Request.Form["isDistinct"]);
多文件循环保存:
for (int i = 0; i < files.Count; i++)
{
var type = files[i].ContentType;
if (type.Contains("image"))
{
switch (type)
{
case "image/jpeg":
suffix = ".jpg";
break;
case "image/png":
suffix = ".png";
break;
case "image/bmp":
suffix = ".bmp";
break;
case "image/gif":
suffix = ".gif";
break;
case "image/pipeg":
suffix = ".jfif";
break;
case "image/x-icon":
suffix = ".ico";
break;
default:
error++;
var obj = new {
code = -1,
msg = "检测到非指定文件格式(jpg/png/bmp/gif/ico/jfif)"
};
msg.AppendLine(JsonHelper.SerializeObject(obj));
continue;
//return Json(new { result = false, messge = "请将图片转化为(jpg/png/bmp/gif/ico/jfif)格式然后上传!" });
}
if (string.IsNullOrWhiteSpace(suffix))
{
error++;
var obj = new
{
code = -1,
msg = "检测到非指定文件格式(jpg/png/bmp/gif/ico/jfif)"
};
msg.AppendLine(JsonHelper.SerializeObject(obj));
continue;
}
var file = "banner/";
var fileName = DateTime.Now.ToStampDateTime() + "_"+i + suffix;
阿里云图床文件存储,底层不予展示:
try
{
var absoluteUri = aliyunOss.UploadObject(files[i].InputStream, file + fileName);
}
catch (Exception e)
{
error++;
var obj = new { code = -2, message = "文件上传失败" };
msg.AppendLine(JsonHelper.SerializeObject(obj));
//return Json(new { result = false, message = "上传失败" });
}
Banner信息存数据库:(底层是数据库保存语句)
var res = new CircleBll().AddCircleBanners(
new Model.CircleBanner() {
ImgUrl = AppConfig.AliyunUrl + file + fileName,
Sex = sex.ToString(),
IsDistinct = isDistinct.ToString(),
OperatorId = account.UserId.ToString()
}
);
if (!res)
{
error++;
var obj = new { code = -3, message = "圈子Banner数据库存储失败" };
}
}
}
return error == 0 ? Json(new { code = 0, msg = "",data = true })
: Json(new { code = error * -1,msg = msg.ToString(),data = false });
}