ASP.Net MVC3 图片上传详解(form.js,bootstrap)
图片上传的插件很多,但很多时候还是不能切合我们的需求,我这里给大家分享个我用一个form,file实现上传四张图片的小demo。完全是用jquery前后交互,没有用插件。
最终效果图如下:
玩过花田人可能有些眼熟,原型就是来自于花田网中的图片上传。
引用的脚本有:
<script src="../../Scripts/jquery-ui-1.9.2.custom.min.js"></script>
<script src="../../Scripts/jquery-1.8.3.js"></script>
<link href="../../Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
<script src="../../Content/bootstrap/js/bootstrap.min.js"></script> <script src="../../Content/JS/form.js"></script>
基本思路:用户点击相关div触发file元素打开浏览框----》用setInterval不断检测file文件是否选中文件---》选中之后触发form自动提交到后台---》后台将文件存储到临时文件夹返回图片在临时文件夹的地址---》窗口提示上传功能并预览图片---》用户点击发布---》后台保存图片(移动到指定文件夹,并存入数据库)
整个过程form和file都是隐藏的。另外的效果
1. 开始的时候只显示一个上传框,前一个上传完成后,显示下一个上传框。并总是显示在最后面。
2. 有图片的时候才能提交和输入描述。
3.上传成功之后,删除后才能再次上传。
Html+css
.uploadbox {
float: left;width: 115px;height: 115px;
background-color: #eeeeee;
margin-right: 10px;color: white;text-align: center;cursor: pointer;
position: relative;display: none;
}
.uploadbox:hover {
background-color: #b4b4b4;
}
.stt{ font-size: xx-small;display: block;}
.add{ vertical-align: baseline;display: block;height: auto;font-size: 8em; height: 40px;padding: 10px;margin-top: 30px}
.imgcontainer{ width: 100%;height: 100%} .imgcontainer img{ max-height: 115px;max-width: 115px;}
.inputdiv{ clear: both;display: block;padding-top: 10px;}
#Remark{ width:478px;}
.infospan{display: none; height: 20px;position: absolute;bottom:;right:;width: 100%;background-color: #00bfff;z-index:;clear: both;opacity: 0.8;}
.closespan{display: none; position: absolute;right: -7px;top: -7px;width: 14px;height: 14px;border-radius: 7px;background-color: white;border: 1px gainsboro solid;color: gray;
font-weight: bold;font-size: medium;
line-height: 16px;
} .closespan:hover{ color: red;}
#imgupload form{ display: none;}
.imguploadmessage{ font-size: small;color: green;float: left;margin-left: 10px;}
.carclose{ cursor: pointer;
background-color: white;opacity:;
position: absolute;z-index:;top:0px;right: -40px;
width: 40px;height:40px;border-radius: 20px;text-align: center;
line-height: 40px;font-size: 2em;color: gray;
}.carclose:hover{ color: green;background-color: #eeeeee}
<div id="imgupload" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4>上传图片</h4>
</div>
<div class="modal-body">
<div class="uploadbox" data-count="0" style="display: inline;">
<span class="closespan" title="删除照片">×</span>
<div class="imgcontainer">
<div class="add">+</div>
<div class="stt">点击上传</div>
</div>
<span class="infospan">
<img src='../../Content/Photos/loading.gif' />正在上传...</span>
</div>
<div class="uploadbox" data-count="0" >
<span class="closespan" title="删除照片">×</span>
<div class="imgcontainer">
<div class="add">+</div>
<div class="stt">点击上传</div>
</div>
<span class="infospan"> <img src='../../Content/Photos/loading.gif' />正在上传...</span>
</div>
<div class="uploadbox"data-count="0" >
<span class="closespan" title="删除照片">×</span>
<div class="imgcontainer">
<div class="add">+</div>
<div class="stt">点击上传</div>
</div>
<span class="infospan"> <img src='../../Content/Photos/loading.gif' />正在上传...</span>
</div>
<div class="uploadbox"data-count="0" >
<span class="closespan" title="删除照片">×</span>
<div class="imgcontainer">
<div class="add">+</div>
<div class="stt">点击上传</div>
</div>
<span class="infospan"> <img src='../../Content/Photos/loading.gif' />正在上传...</span>
</div>
<div class="inputdiv"><input type="text" disabled="disabled" id="Remark" name="Remark" placeholder="补充说明下~"/></div>
</div>
<div class="modal-footer">
上传大小在8k-10M之间 <span class="imguploadmessage"></span>
<button class="btn btn-success " disabled="disabled" id="imgsubmit">发布</button>
<form action="/User/UpLoadPhoto" method="POST" enctype="multipart/form-data" name="ImgForm" id="ImgForm">
<input type="file" name="file" id="imgFlie" required="required" />
<input type="submit" name="subt" value="上传图片" />
</form>
</div> </div>
Jquery:
//图片上传-------------------------------------imgupload--------------------- var imgbox = {};//用来获取当前点击的 uploadbox
var childs = $(".imgcontainer:eq(0)").html();// 先保存内部元素,上传完成之后方便恢复到最初状态
$(".uploadbox").click(function () {
var tag = $(this).attr("data-count");//用来判断是否已经含有照片
if (tag == "1") return false;
$("#imgFlie").click();
imgbox = $(this);
var stm1 = setInterval(function () {
var imgstr = $("#imgFlie").val(); //检测file元素是否已经含有文件
if (imgstr != "") {
clearInterval(stm1);
$("#ImgForm input[type='submit']").click();
}
}, 500);
return false;
}); // 取消照片
$(".closespan").click(function (e) {
e.stopPropagation();
var sum = $(".uploadbox img").length;
// 保证有一个框可以让用户再次选择 需要显示childs 设置data-count属性 必要的再隐藏
var imgsrc = $(this).next().find("img").attr("src");
$(this).next().html("").append(childs);
// 隐藏关闭和成功提示
$(this).hide();
$(this).siblings(".infospan").hide();
$(this).parent().attr("data-count", 0).insertBefore($(".inputdiv"));; if (sum < 4) {//说明此时是有一个再准备状态,这个可以直接做删除处理
// 设置data-count 并隐藏父级
$(this).parent().hide();
//需要移位 保证准备状态的总是在最后一个
}
// 清除session 减少一个字符串
if (imgsrc != undefined) {
$.post("/User/DeleteImg", { str: imgsrc }, function () { });
}
if (sum == 1) {
$('#Remark,#imgsubmit').attr("disabled", "disabled");// 说明这个时候还没有图片上传,所以要禁止发布键和描述框
} }); //----------上传图片---------------------------------------------
$("#imgsubmit").click(function () {
var imgcontent = $.trim($("#Remark").val());
$.post("/User/SaveImgs", { content: imgcontent }, function (data) {
if (data == 1) {
//清除content
$(".imgcontainer").html(childs);
//隐藏进度条和关闭键
$(".closespan,.infospan").hide();
$(".imguploadmessage").html("上传成功!");
//禁止输入框和提交按钮
$('#Remark,#imgsubmit').attr("disabled", "disabled");
//去掉data-count 属性 显示第一个;
$(".uploadbox").attr("data-count", 0).hide().eq(0).show();
//清空
$("#Remark").val("");
var stt = setTimeout(function () {
$("#imgupload").modal('hide');
$(".imguploadmessage").html("");
clearTimeout(stt);
}, 1000);
}
});
}); $('#ImgForm').ajaxForm({//用到form.js 提交form
beforeSend: function () {
imgbox.find(".infospan").show();//显示正在上传...
},
success: function (data) {
$("#imgFlie").val("");//
imgbox.find(".imgcontainer").html(data);//.hide()
var img = imgbox.find(".imgcontainer").find("img").attr("src");
if (img != undefined) {//表示上传成功
//解禁
$('#Remark').removeAttr("disabled");
$('#imgsubmit').removeAttr("disabled");
imgbox.find(".infospan,.closespan").show();
imgbox.find(".infospan").html("上传成功!");
//显示下一个
//imgbox.next().show();
$(".uploadbox:hidden").eq(0).show(); imgbox.attr("data-count", "1");
} else {
imgbox.find(".infospan,.closespan").hide();
}
// alert(img);
}, complete: function (xhr) {
$("#imgFlie").val("");
}
});
后台controller的代码
[HttpPost]
public void UpLoadPhoto(HttpPostedFileBase file)
{
var res = CheckImg(file);
if (res == "ok")
{
var fileName = file.FileName;//Path.GetExtension() 也许可以解决这个问题,先不管了。
var pathtemp = Path.Combine(Server.MapPath("../Content/TempFile/"), fileName);//先存入临时文件夹
var scrtemp = Path.Combine("../../Content/TempFile/", fileName);//图片展示的地址 var list = Session["Imgscr"] as List<string>;
var slist = Session["ImgServerscr"] as List<string>;
if (list != null)
{
list.Add(scrtemp);
}
else
{
list = new List<string> { scrtemp };
Session["Imgscr"] = list;
}
if (slist != null)
{
slist.Add(pathtemp);
}
else
{
slist = new List<string> { pathtemp };
Session["ImgServerscr"] = slist;
} file.SaveAs(pathtemp);
Response.Write("<img src='../../Content/TempFile/" + fileName + "' /> ");
}
else
{
Response.Write(res);
}
} /// <summary>
/// 删除预览中的照片
/// </summary>
/// <param name="str">这个str 已经是处理过的,不是之前上传的图片名称</param>
public void DeleteImg(string str)
{
//删除地址 删除文件
var list = Session["Imgscr"] as List<string>;
if (list == null) return;
var index = list.IndexOf(str);
var slist = Session["ImgServerscr"] as List<string>;
if (slist != null && index != -)
{
var imgone = slist[index];
if (imgone != null)
{
var img = new FileInfo(imgone);
if (img.Exists) img.Delete();
}
}
list.Remove(str);
} private string CheckImg(HttpPostedFileBase file)
{
if (file == null) return "图片不能空!";
if (file.ContentLength / > )
{
return "图片太大";
}
if (file.ContentLength / < )
{
return "图片太小!";
}
var image = GetExtensionName(file.FileName).ToLower();
if (image != ".bmp" && image != ".png" && image != ".gif" && image != ".jpg" && image != ".jpeg")// 这里你自己加入其他图片格式,最好全部转化为大写再判断,我就偷懒了
{
return "格式不对";
} var scrtemp = Path.Combine("../../Content/TempFile/", file.FileName);//图片展示的地址
var list = Session["Imgscr"] as List<string>;
if (list != null && list.Find(n => n == scrtemp) != null)
{
return "同样的照片已经存在!";
} return "ok";
} public JsonResult SaveImgs(string content)
{
var uid = CheckValid();
if (_uName == null) _uName = GetUserNameById(uid); string path = Path.Combine(HttpContext.Server.MapPath("../Content/UploadFiles/"), _uName, "Photos", "ImgBox");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
var list = Session["Imgscr"] as List<string>;
var finallist = new List<string>();
if (list == null) return Json();
foreach (var str in list)
{
var scrtemp1 = Server.MapPath(str.Substring(, str.Length - ));//去掉第一个../
var img = new FileInfo(scrtemp1);
if (img.Exists)
{
var image = GetExtensionName(img.Name);
//处理照片名称
var imgname = string.Format("{0:yyyMMdd}", DateTime.Now).Replace("/", "") + DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture).Substring(, ) + image;
var scrdestination = Path.Combine(HttpContext.Server.MapPath("../Content/UploadFiles/"), _uName, "Photos", "ImgBox", imgname); var scrshow = Path.Combine(("../../Content/UploadFiles/"), _uName, "Photos", "ImgBox", imgname);
finallist.Add(scrshow);
//移动照片
img.MoveTo(scrdestination);
//存入imgbox
var box = new Iamgbox
{
ActionTime = DateTime.Now,
BoxName = _uName,
ImgUrl = scrshow,
IsValid = true, //默认是正规合适的图片 不合适在检举
PraiseCount = ,
Remark = content,
UserId = uid,
VisitCount = ,
};
LoveDb.Add(box);
};
}
if (finallist.Count() != )
{
var sbstr = new StringBuilder("<br/><div class='imgtigger'>");
foreach (var str in finallist)
{
sbstr.Append("<img src='" + str + "' />");
}
sbstr.Append("</div>");
var state = new State
{
ActionTime = DateTime.Now,
Content = (content == "" ? string.Format("刚刚上传了{0}张照片:", finallist.Count) : content)+sbstr,
PraiseCount = ,
StateType = StateType.Image.ToString(),
UserId = uid
};
LoveDb.Add(state);
Session.Remove("Imgscr");
Session.Remove("ImgServerscr");
} return Json();
}
public string GetExtensionName(string fileName)
{
if (fileName.LastIndexOf("\\", StringComparison.Ordinal) > -)//在不同浏览器下,filename有时候指的是文件名,有时候指的是全路径,所有这里要要统一。
{
fileName = fileName.Substring(fileName.LastIndexOf("\\", StringComparison.Ordinal) + );//IndexOf 有时候会受到特殊字符的影响而判断错误。加上这个就纠正了。
}
return Path.GetExtension(fileName.ToLower());
}
到这,这个过程就完成了,希望对你有帮助。
Demo 下载地址: http://download.csdn.net/detail/stoneniqiu/6581841
没有积分的留个邮箱吧。
ASP.Net MVC3 图片上传详解(form.js,bootstrap)的更多相关文章
- Newtonsoft.Json C# Json序列化和反序列化工具的使用、类型方法大全 C# 算法题系列(二) 各位相加、整数反转、回文数、罗马数字转整数 C# 算法题系列(一) 两数之和、无重复字符的最长子串 DateTime Tips c#发送邮件,可发送多个附件 MVC图片上传详解
Newtonsoft.Json C# Json序列化和反序列化工具的使用.类型方法大全 Newtonsoft.Json Newtonsoft.Json 是.Net平台操作Json的工具,他的介绍就 ...
- MVC图片上传详解 IIS (安装SSL证书后) 实现 HTTP 自动跳转到 HTTPS C#中Enum用法小结 表达式目录树 “村长”教你测试用例 引用provinces.js的三级联动
MVC图片上传详解 MVC图片上传--控制器方法 新建一个控制器命名为File,定义一个Img方法 [HttpPost]public ActionResult Img(HttpPostedFile ...
- MVC图片上传详解
MVC图片上传--控制器方法 新建一个控制器命名为File,定义一个Img方法 [HttpPost]public ActionResult Img(HttpPostedFileBase shangch ...
- Multipart/form-data POST文件上传详解
Multipart/form-data POST文件上传详解 理论 简单的HTTP POST 大家通过HTTP向服务器发送POST请求提交数据,都是通过form表单提交的,代码如下: <form ...
- [转]人人网首页拖拽上传详解(HTML5 Drag&Drop、FileReader API、formdata)
人人网首页拖拽上传详解(HTML5 Drag&Drop.FileReader API.formdata) 2011年12月11日 | 彬Go 上一篇:给力的 Google HTML5 训练营( ...
- Multipart/form-data POST文件上传详解(转)
Multipart/form-data POST文件上传详解 理论 简单的HTTP POST 大家通过HTTP向服务器发送POST请求提交数据,都是通过form表单提交的,代码如下: <form ...
- ASP.NET MVC图片上传前预览
回老家过春节,大半个月,在家的日子里,吃好睡好,人也长了3.5Kg.没有电脑,没有网络,无需写代码,工作上相关的完全放下......开心与父母妻儿过个年,那样的生活令Insus.NET现在还在留恋.. ...
- asp.net多图片上传实现程序代码
下面是一个完整的asp.net同时支持多图片上传一个实现,有需要的朋友可参考一下,本文章限制同时可上传8张图片,当然大可自己可修改更多或更少. 前台代码如下: 复制代码代码如下: <% @ Pa ...
- asp.net多图片上传同时保存对每张图片的描述
前台aspx //图片预览和描述 function previewImage(file) { var div = document.getElementById('preview'); div.inn ...
随机推荐
- SQL Server客户端请求
SQL Server是客户端 - 服务器平台.通过发送包含对数据库请求的命令是与后端数据库进行交互的唯一方法.你的应用程序和数据库之间通信的协议被称为TDS(表格数据流协议). 应用程序可以使用该协议 ...
- Jenkins配置自动发送邮件,成功!
Jenkins自动发送邮件配置: 打开"系统管理"--"系统设置" 在"Jenkins Location"设置系统管理员地址(重要:不能省略 ...
- eclipse控制台乱码
- winform快速开发平台 -> 工作流组件(仿GooFlow)
对于web方向的工作流,一直在用gooflow对于目前我的winform开发平台却没有较好的工作流组件. 针对目前的项目经验告诉我们.一个工作流控件是很必要的. 当然在winform方面的工作流第三 ...
- Android Studio导入第三方类库的方法(转)
转自:链接 本人也刚刚开始尝试做android app的开发,听说android studio是Google支持的android 应用开发工具,所以想应该肯定比Eclipse好用吧,反正以前没有jav ...
- Android自定义组件
[参考的原文地址] http://blog.csdn.net/l1028386804/article/details/47101387效果图: 实现方式: 一:自定义一个含有EditText和Butt ...
- 【CentOS】LAMP
文章需要整合,学习需要归纳,博主把一连四篇的LAMP合并成为一片长篇的大部头,并梳理了一下他们的关系,希望对各位有所帮助 最近一次更新:2016年12月21日21:38:31 本文为博主JerryCh ...
- tomcat的安全配置(禁用http方法,部署多个应用,启用从安全cookie,指定错误页面和显示信息)
配置版本:tomcat6 1,虚拟路径,可以配置多个host在一个tomcat中,docbase是web应用目录,此处在server.xml中添加应用配置,要让server.xml配置生效需要重启to ...
- Swift学习之熟悉控件
最近是比较清闲一些的,对于一个开发者来说,这也是一个很好的充电机会.以前做项目都是使用Objective-C去开发,但我们都知道,Swift语言从2014年的出现到现在,一步一步变的完善,渐渐变的受欢 ...
- 【历史】JavaScript和Java没啥关系!————JavaScript简史
文章的开始先上张图: 图片拍摄自北京图书大厦,代表着现在国内应该是绝大部分书店的现状--Javascript书籍放在Java类当中.甚至很多业内人也一直认为Javascript是Java语言在浏览器内 ...