效果预览:
后台代码:
#region iframe上传图片
/// <summary>
/// iframe上传图片
/// </summary>
/// <returns></returns>
public ActionResult upload_pic()
{
if (IsPost)
try
{
HttpPostedFileBase file = Request.Files["pic1"];
if (file == null)
throw new Exception("请选择文件!");
string fileName = file.FileName;//获取描述
string newFileName = Guid.NewGuid().ToString("N");//使用guid生成新文件名
string fileTypes = "JPG、GIF、PNG".ToLower();
double maxSize = 3 * 1024 * 1024;
ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));
string fileExt = Path.GetExtension(fileName).ToLower();
Hashtable hash = new Hashtable();
if (file.InputStream == null || file.InputStream.Length > maxSize)
throw new Exception("请上传3M以内的JPG、GIF、PNG图片。!");
if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split('、'), fileExt.Substring(1).ToLower()) == -1)
throw new Exception("请上传3M以内的JPG、GIF、PNG图片。!");
string dirPath = Server.MapPath("~/small/");
if (!Directory.Exists(dirPath))
Directory.CreateDirectory(dirPath);
//保存文件
newFileName += System.IO.Path.GetExtension(file.FileName);//注意加上扩展名
file.SaveAs(dirPath + newFileName);//如果要保存到其他地方,注意修改这里
System.Drawing.Image Img = System.Drawing.Image.FromFile(dirPath + newFileName);
int w = 500;
string w_str = string.Format("width:{0}px;", w > Img.Width ? Img.Width : w);
return Content("<script>parent.UpdateMsg('" + fileName + "','" + newFileName + "','" + w_str + "');</script>");
}
catch (Exception ex)
{
return Content("<script>alert('很抱歉:" + ex.Message + "');parent.cancel_pic_no();</script>");
}
return Content("<script>alert('很抱歉:操作错误');parent.cancel_pic_no();</script>");
}
private string Js(string v)
{
//此函数进行js的转义替换的,防止字符串中输入了'后造成回调输出的js中字符串不闭合
if (v == null) return "";
return v.Replace("'", @"\'");
}
#endregion
Html代码:
<div class="W_formup">
<!--uppic start-->
<!--隐藏的iframe来接受表单提交的信息-->
<iframe name="ajaxifr_upload_target" style="display: none;"></iframe>
<!--这里设置target="ajaxifr_upload_target",这样表单就提交到iframe里面了,和平时未设置target属性时默认提交到当前页面-->
<!--注意一点的是使用iframe时在提交到的页面可以直接输出js来操作父页面的信息,一般的ajax提交文本信息时你需要返回信息,如果是js信息你还得eval下-->
<form action="/Home/upload_pic" method="post" enctype="multipart/form-data" target="ajaxifr_upload_target" name="pic_upload" id="pic_upload">
<input type="file" class="input_f" name="pic1"></form>
</div>
<div class="W_loading hide"><span>图片正在上传,请等待...</span></div>
<div class="W_picimgs hide"></div>
JS代码:
function cancel_pic_no()
{
$(".W_formup").show().next().hide().next().hide();
}
function UpdateMsg(des, filename, w_str)
{
//此函数用来提供给提交到的页面如/Comm/upload输出js的回调,更新当前页面的信息
if (filename == '' || des == '')
{
$(".W_formup").show().next().hide().next().hide();
alert('未上传文件!');
return false;
}
$(".W_formup").hide().next().hide().next().show();
//处理图片信息
$(".W_picimgs").html('<img src="/small/' + filename + '" style="' + w_str + '"/>');
}
$(function ()
{
//上传文件
$(".input_f").change(function ()
{
$(".W_formup").hide().next().show().next().hide();
$("#pic_upload").submit();
//请上传3M以内的JPG、GIF、PNG图片。
});
});