某些時候當咱們作登記頁面的時候可能須要上傳圖片,並實現即時預覽的功能。php
若是隻是預覽而不上傳,能夠使用ImagePreview來實現,方便簡單。若是須要上傳,那麼你也能夠使用uploadify無刷新上傳插件來實現,並在上傳完畢後更改img標籤的src路徑來實現預覽功能,此插件自帶php實例,網上也有不少Asp.Net的實例可供參考。node
好了,進入正題吧,首先附上HTML代碼:jquery
<asp:Image ID="imgexper" Width="129px" Height="172px" ImageUrl="~/images/nophoto.gif" runat="server" /> <div> <asp:FileUpload ID="fuimg" runat="server" onchange="if(this.value)ispic(this.value,this);" /> <asp:HiddenField ID="hfpath" runat="server" /> </div>
JS代碼:ajax
//======去除空格
String.prototype.Trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
//======根據ID獲取對象的值並去除空格
var $val = function (id) {
if (typeof id == "string") {
try {
return document.getElementById(id).value.Trim();
}
catch (Error) {
alert("ID錯誤!");
}
}
else if (typeof id == "object") {
try {
return id.value.Trim();
}
catch (Error) {
alert("參數錯誤!");
}
}
else {
alert("參數錯誤!");
}
};
function ispic(file, node) { var pic = "../images/"; if (file) { var suffix = file.split("."); var num = suffix.length - 1; var name = suffix[num].toLowerCase(); if (name != "jpeg" && name != "jpg" && name != "gif" && name != "bmp" && name != "png") { alert("上傳類型錯誤,暫只支持.jpeg|.jpg|.gif|.bmp|.png格式!"); node.outerHTML = node.outerHTML; clearphoto(pic); //清理 } else { var oldpath = $val("hfpath"); var pageurl = "ExpertPhotoAjax.aspx?oldpath=" + oldpath; var options = { url: pageurl, type: "POST", dataType: "HTML", beforeSend: function () { document.getElementById("imgexper").src = pic + "wating.gif"; }, success: function (path) { if (path != "") { var links = path.split(","); document.getElementById("hfpath").value = links[0]; document.getElementById("imgexper").src = links[1]; } else { clearphoto(pic); alert("加載失敗,請從新選擇圖片!"); } }, error: function () { clearphoto(pic); alert("加載失敗,請從新選擇圖片!"); } }; // 將options傳給ajaxForm jQuery('#form1').ajaxSubmit(options); } } } function clearphoto(pic) { document.getElementById("hfpath").value = ""; document.getElementById("imgexper").src = pic + "noimg.gif"; }
C#代碼:ui
//變量定義 string oldpath = Request.QueryString["oldpath"].ToString(); string path = ""; //刪除以前上傳的圖片 if (oldpath != "") { oldpath = HttpContext.Current.Server.MapPath(oldpath); if (System.IO.File.Exists(oldpath)) { System.IO.File.Delete(oldpath); } } //上傳新圖片 try { HttpFileCollection files = Context.Request.Files; if (files.Count > 0) { string photoname = DateTime.Now.ToString("yyyyMMddHHmmss"); HttpPostedFile file = files[0]; if (file.ContentLength > 0) { //建立目錄 path = "~/UpFile/Photos/"; if (!Directory.Exists(HttpContext.Current.Server.MapPath(path))) { Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path)); } string fileName = file.FileName; string extension = Path.GetExtension(fileName); path += photoname + extension; file.SaveAs(HttpContext.Current.Server.MapPath(path)); if (flag == 1) path += path.Replace("~/", ","); else path += path.Replace("~", ",.."); } } } catch (Exception) { path = ""; } Response.Write(path); Response.End();
PS:使用的此方法的頁面必須引用jquery.form.jsthis