<div id="localImag" style="width: 328px; float: left; height: 113px;"> <img id="preview" src="SearchCompanyPhoto.ashx" width="140" height="150" /> </div>
一般處理常式
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Text;using BLL;using System.Web.SessionState;//引入讀寫操作using System.IO;namespace GoodCommunitySystem{ /// <summary> /// SearchCompanyPhoto 的摘要說明 /// </summary> public class SearchCompanyPhoto : IHttpHandler, IReadOnlySessionState { public void ProcessRequest(HttpContext context) { //當session有值的時候才能夠上傳頭像 if (context.Session["UserName"] != null){ companyBLL companybll = new companyBLL(); Entity.companyEntity encompanyInfo = new Entity.companyEntity(); StringBuilder strWhere = new StringBuilder(); //拿到session中存在的使用者id值 string userID = context.Session["UserID"].ToString(); string userName=context.Session["UserName"].ToString(); encompanyInfo = companybll.GetEntity(userID); //擷取頭像地址 string HeadImg = encompanyInfo.HeadImg; //把頭像地址轉換為絕地地址 string img = context.Server.MapPath(HeadImg); // 以二進位方式讀檔案 FileStream aFile = new FileStream(img, FileMode.OpenOrCreate, FileAccess.ReadWrite); // 建立一個位元據流讀入器,和開啟的檔案關聯 BinaryReader brMyfile = new BinaryReader(aFile); // 把檔案指標重新置放到檔案的開始 brMyfile.BaseStream.Seek(0, SeekOrigin.Begin); //擷取照片的位元組數組 byte[] photo = brMyfile.ReadBytes(Convert.ToInt32(aFile.Length.ToString())); // 關閉以上new的各個對象 brMyfile.Close(); context.Response.BinaryWrite(photo); } else { return; } } public bool IsReusable { get { return false; } } }}
HTML
<asp:FileUpload ID="FileUpload1" runat="server" onchange="javascript:setImagePreview(this,localImag,preview);" style="width: 245px; margin-left: -125px; "/><input id="Button1" type="button" onclick="SavePhoto()" value="確認上傳頭像" style="margin-left: 200px;"/>
JS
function SavePhoto() { document.getElementById("test").value = "SavePhoto";//設定表示為後台調不同方法資料 var form = document.forms["TabData"]; form.action = "EditCompanyInfo.aspx"; form.method = "POST"; form.submit(); }
using BLL;using Entity;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace GoodCommunitySystem{ public partial class EditCompanyInfomation : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { var test = Request.Form["test"]; //當session中不存在值,頁面重新導向到首頁 if (Session["UserName"] == null) { Response.Redirect("default.aspx"); } else { if (test == "SavePhoto") { //上傳頭像 UpdatePhoto(); } } } companyBLL companybll = new companyBLL(); companyEntity encompany = new companyEntity(); public void UpdatePhoto() { if (Session["UserName"] == null) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('您尚未登入,請登入!');</script>"); //Response.Write("<script language='javascript'>alert('請重新登入!');</script>"); return; } if (this.FileUpload1.FileContent.Length <= 0) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('請您重新上傳頭像,謝謝!');</script>"); return; } if (this.FileUpload1.FileContent.Length >= 200000) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('照片不能超過200KB!');</script>"); return; } String fullfilename = this.FileUpload1.PostedFile.FileName; //擷取圖片的絕對路徑 String filename = fullfilename.Substring(fullfilename.LastIndexOf("\\") + 1);//擷取圖片的名稱 String type = filename.Substring(filename.LastIndexOf(".") + 1).ToLower(); //擷取圖片的格式(類型) String Rename = Session["UserName"] + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"); //使用者名稱+時間命名,避免上傳圖片命名重複 string varToDirectory = Request.PhysicalApplicationPath + "touxiang"; //專門存放使用者相簿的檔案 //判斷檔案是否存在,不存在則建立該檔案 if (!Directory.Exists(varToDirectory)) { Directory.CreateDirectory(varToDirectory); } if (type == "jpg" || type == "png" || type == "jpeg" || type == "gif") { companyEntity enCompanyInfo = new companyEntity(); enCompanyInfo.UserID = Session["UserID"].ToString(); enCompanyInfo.HeadImg = "touxiang/" + Rename + "." + type; //資料庫中中圖片的路徑 //圖片首先上傳至目錄下 FileUpload1.SaveAs(Server.MapPath("touxiang") + "/" + Rename + "." + type);//將圖片以相對路徑儲存,並以目前時間命名 //添加記錄成功後 if (companybll.UpdateHeadImg(enCompanyInfo)) { Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('上傳照片成功');</script>"); DataListBind(); } else { //Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('刪除照片失敗,請重新上傳!');</script>"); return; //Response.Write("<script language='javascript'>alert('上傳照片失敗,請重新上傳!');</script>"); } } else { Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('您選擇的照片格式有誤,請重新選擇!');</script>"); //Response.Write("<script language='javascript'>alert('您選擇的照片有誤,請重新選擇!');</script>"); } } /// <summary> /// 綁定資料 /// </summary> public void DataListBind() { string UserID = Session["UserID"].ToString(); encompany = companybll.GetEntity(UserID); } }}