一.效果图:
开发框架:MVC,Layui
列表主界面这里就不展示了,可以去看看这篇文章:Layui项目实战,这里讲的是“上传Banner”界面功能:
其中包括,多文件上传,预览,后台接收,保存,仅此而已
二.项目代码:
1.前端Html代码
head头部代码块:
注意:这里引用的是Layui和jQuery插件,不过重点功能还是在jQuery,Layui只是起到样式效果
<head>
<meta name="viewport" content="width=device-width" />
<title>PushCircleBanner</title>
<link href="~/Scripts/layui/css/layui.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.3.1.js"></script>
<script src="~/Scripts/layui/layui.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 80%;
height: 80vh;
margin: auto;
}
.box p {
height: 30px;
margin: 10px;
}
#file{
display:none;
}
.ImgsBox img{
width:100px;
height:100px;
}
.select,input{
width:200px;
}
</style>
</head>
body代码块:
注意:这里既然是文件上传,重点自然是input[“file”],multiple=“multiple"多文件上传,accept=”.png,.jpg,.jpeg,.bmp,.gif,.jfif,.ico "限制允许选择的文件类型
<div class="box">
<p>性别:</p>
<p class="layui-input-inline">
<select name="sex" class="sex layui-input select">
<option value="0" selected>全部</option>
<option value="1">男</option>
<option value="2">女</option>
</select>
</p>
<p>是否去重:</p>
<p class="layui-input-inline">
<select name="isDistinct" class="isDistinct layui-input select">
<option value="0" selected>否</option>
<option value="1">是</option>
</select>
</p>
<p>图片上传:</p>
<p>
<input type="button" class="layui-btn" name="name" onclick="$('#file').click()" value="上传" />
<input id="file" type="file" multiple="multiple" name="img" value="上传" accept=".png,.jpg,.jpeg,.bmp,.gif,.jfif,.ico " onchange="PushFiles()" />
</p>
<p><input type="button" class="layui-btn submit" onclick="Save()" value="保存" /></p>
<div class="ImgsBox">
</div>
</div>
Js代码块:
注意:PushFiles方法,由点击显示的上传按钮,再触发隐藏的input[“file”]按钮的点击方法,改变files值后触发该方法,实现多文件上传效果,也是这里前端界面展示的重点
<script>
var files;
function PushFiles() {
$('.ImgsBox').html('');
files = document.getElementById('file').files;
if (files && files.length > 0) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var URL = window.URL || window.webkitURL;
var imgURL = URL.createObjectURL(file);
console.log(imgURL);
var img = $('<img src="" />');
img.attr('src', imgURL);
$('.ImgsBox').append(img);
}
}
}
注意:Save方法,由点击保存按钮触发,js的FormData对象进行表单参数收集,ajax再通过文件传输的方式,提交到后台
function Save() {
if (files && files.length > 0) {
var formData = new FormData();
formData.append('sex', $('.sex').val());
formData.append('isDistinct', $('.isDistinct').val());
for (var i = 0; i < files.length; i++) {
formData.append('img_'+i,files[i] );
}
$.ajax({
url: '/Circle/PushBanner',
data: formData,
type: 'POST',
cache: false,//这个参数是jquery特有的,不进行序列化,因为我们不是json格式的字符串,而是要传文件
processData: false, //注意这里一定要设置contentType:false,不然会默认为传的是字符串,这样文件就传不过去了
contentType: false,
//dataType: "json",
success: function (res) {
if (res.code == 0) {
var index = parent.layer.getFrameIndex(window.name);//先得到当前iframe层的索引
parent.layer.close(index);//再执行关闭
} else {
alert(res.msg);
}
}
})
} else {
alert("请选择上传文件!");
}
}
</script>
2.后台C#代码
注意:下面的后台代码块,只要把间隔的注意提示去掉,就能拼接出完整的后台代码
/// <summary>
/// 图片批量上传
/// </summary>
/// <returns></returns>
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;
阿里云图床文件存储,底层不予展示:文章来源:https://www.toymoban.com/news/detail-583123.html
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信息存数据库:(底层是数据库保存语句)文章来源地址https://www.toymoban.com/news/detail-583123.html
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 });
}
到了这里,关于C# MVC 多图片上传预览的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!