Net Web端无刷新上传图片
自己搞的一个web端上传图片功能,思路是在页面放一个iframe,在src指向的页面实现上传并返回图片路径,缺点是会产生很多垃圾文件,待解决
大概代码如下:
用户控件代码,文件名UCUpload.ascx:
前台代码:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="UCUpload.ascx.cs" Inherits="jc.WebFile.ErLive.Site.Custom.UCUpload" %> <iframe src="/ErLive/Site/Custom/UploadFile.aspx" id="frameUpload" runat="server" scrolling="no" frameborder="0" ></iframe>
后台代码:
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace jc.WebFile.ErLive.Site.Custom { public partial class UCUpload : System.Web.UI.UserControl { #region 公共参数 /// <summary> /// 控件宽 /// </summary> public int frameWidth = 100; /// <summary> /// 控件高 /// </summary> public int frameHeight = 100; /// <summary> /// 文件大小kb /// </summary> public int fileSize = 1024; /// <summary> /// 保存路径的文本框 /// </summary> public string txtName = "txtImg"; #endregion protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { frameUpload.Style.Add("width", frameWidth + "px"); frameUpload.Style.Add("height", frameHeight + "px"); frameUpload.Attributes.Add("lang", txtName); frameUpload.Attributes.Add("data-fileSize", fileSize.ToString()); } } } }
上传文件代码,文件名UploadFile.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UploadFile.aspx.cs" Inherits="jc.WebFile.ErLive.Site.Custom.UploadFile" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" style="*overflow: hidden;"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style> .FileMainUploadCss { position: relative; cursor: pointer; filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0); opacity: 0; float: left; top: 0; left: 0px; z-index: 9; border: 0px; font-size: 50px; } body { margin: 0 0; padding: 0 0; overflow: hidden; } .showImg { position: absolute; top: 0px; left: 0px; z-index: 8; } </style> </head> <body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="xFileUpload" onchange="return fileChange(this)" runat="server" CssClass="FileMainUploadCss" BorderStyle="None" /> <img id="imgShow" runat="server" class="showImg" /> <asp:Button ID="btnSave" runat="server" Text="Button" OnClick="btnSave_Click" Style="display: none" /> <asp:TextBox ID="txtUImg" runat="server" Text="" Style="display: none"></asp:TextBox> </div> <input type="hidden" id="hidFildSize" runat="server" value="1024" /> </form> <script type="text/javascript"> var thisId = window.parent.xGetFrameId(this); //var frame = window.top.document.getElementById(thisId); var frame = this.parent.document.getElementById(thisId); var imgShow = document.getElementById("imgShow"); var txtUImg = document.getElementById("txtUImg"); var xFileUpload = document.getElementById("xFileUpload"); //设置图片显示的宽高 imgShow.width = frame.clientWidth; imgShow.height = frame.clientHeight; //设置fileupload的宽高 xFileUpload.style.cssText += ";width:" + (imgShow.width) + "px;height:" + (imgShow.height) + "px;"; //父级页面存储图片url var txtName = frame.lang; //父级页面存储图片大小 //alert(frame.dataset.filesize); //document.getElementById("hidFildSize").value = frame.dataset.filesize; document.getElementById("hidFildSize").value = frame.getAttribute("data-fileSize"); //解决 IE 兼容问题 function FileSubmit(t) { if (t.value != "") { if (t.value.length > 0) { var strImg = t.value.substring(t.value.length - 4, t.value.length); strImg = strImg.toLowerCase(); if (strImg != ".gif" && strImg != ".jpg" && strImg != ".png" && strImg != ".bmp" && strImg != "jpeg") { alert("照片格式不正确!"); return (false); } } document.getElementById("btnSave").click(); return (true); } } //初始加载时判断父级页面是否存在图片路径 function SetImgSrc() { var PtxtName = window.parent.document.getElementById(frame.lang); if (txtUImg.value == "") { if (PtxtName.value == "") { imgShow.src = "/ErLive/img/no.jpg"; } else { imgShow.src = PtxtName.value; } //alert(imgShow.src + " = " + imgShow.src.length + " txtUImg.value = " + PtxtName.value); } else { //上传新图片后将路径返回给父级页面 PtxtName.value = txtUImg.value; } } SetImgSrc(); //判断文件大小 var isIE = /msie/i.test(navigator.userAgent) && !window.opera; function fileChange(target) { var fileSize = 0; if (isIE && !target.files) { var filePath = target.value; try { var fileSystem = new ActiveXObject("Scripting.FileSystemObject"); var file = fileSystem.GetFile(filePath); fileSize = file.Size; } catch (e) { alert(e + "\n 跳出此消息框,是由于你的activex控件没有设置好,\n" + "你可以在浏览器菜单栏上依次选择\n" + "工具->internet选项->\"安全\"选项卡->自定义级别,\n" + "打开\"安全设置\"对话框,把\"对没有标记为安全的\n" + "ActiveX控件进行初始化和脚本运行\",改为\"启动\"即可"); return false; } } else { fileSize = target.files[0].size; } var fsize = document.getElementById("hidFildSize").value; fsize = parseFloat(fsize); fileSize = parseInt(fileSize); var size = fsize / 1024; size = parseInt(size); if (fileSize / 1024 > fsize) { alert("图片大小不得超过" + ((size > 0) ? (size + "M") : (fsize + "KB"))); return false; } FileSubmit(target); return true; } </script> </body> </html>
后台代码:
using jc.Common; using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace jc.WebFile.ErLive.Site.Custom { public partial class UploadFile : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnSave_Click(object sender, EventArgs e) { string SaveUrl = "/Upload/"; HttpFileCollection HFC = Request.Files; HttpPostedFile UserHPF = HFC[0]; double fileSize = 0; double.TryParse(hidFildSize.Value.ToString(), out fileSize); double fSize = fileSize / 1024; if (UserHPF.ContentLength / 1024.00 > fileSize) { Response.Write("<script>alert('图片大小不超过" + ((fSize > 0) ? (fSize + "M") : (fileSize + "KB")) + "')</script>"); return; } string FileName = HUpload.Upload(xFileUpload, Server.MapPath(SaveUrl), true); if (FileName == "") { Response.Write("<script>alert('上传图片超过大小')</script>"); } else { imgShow.Src = SaveUrl + FileName; txtUImg.Text = SaveUrl + FileName; } //imgShow.Src = ""; //txtUImg.Text = "/Upload/201512/1.jpg"; } } }
需要的上传函数HUpload.Upload()函数如下:
/// <summary> /// 上传图片,不生成缩略图,文件大小不能超过1M,文件格式为:Jpg,Gif,Bmp,Png /// </summary> /// <param name="FileUpload">上传控件ID</param> /// <param name="imgpath">上传文件存放路径</param> /// <param name="b">是否生成年月目录,及返回此目录的字符串</param> /// <returns>图片名称</returns> public static string Upload(FileUpload FileUpload, string imgpath, bool b) { string filename = ""; string str2 = ""; string path = ""; if (b) { path = Path.Combine(imgpath, DateTime.Now.ToString("yyyyMM")); } else { path = imgpath; } if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string fileName = FileUpload.PostedFile.FileName; string str5 = FileUpload.PostedFile.ContentType.ToLower(); if ((str5.Equals("image/png") || str5.Equals("image/gif")) || str5.Equals("image/bmp") || str5.Equals("image/x-png") || (str5.Equals("image/jpg") || str5.Equals("image/jpeg") || str5.Equals("image/pjpeg"))) { string str6 = Path.GetExtension(fileName).ToLower(); str2 = DateTime.Now.ToString("yyyyMMddHHmmss") + str6; filename = Path.Combine(path, str2); try { FileUpload.PostedFile.SaveAs(filename); if (b) { return (DateTime.Now.ToString("yyyyMM") + "/" + str2); } return str2; } catch { return ""; } } throw new Exception("上传文件类型只能为:Jpg,Gif,Bmp,Png!"); }
使用方法:
<!--引入用户控件--> <%@ Register Src="~/PublicUserControl/Upload/UCUpload.ascx" TagPrefix="uc1" TagName="UCUpload" %> <!--用于显示、上传图片--> <uc1:UCUpload runat="server" ID="UCUploadOne" frameWidth="100" frameHeight="100" txtName="hidImgOne" fileSize="500" /> <!--用于存储图片路径,id与uc1:UCUpload内的txtName参数对应--> <input id="hidImgOne" type="text" style="display: none" runat="server" />