狀況描述:
需要上傳檔案,但是不想要儲存到實體路徑下,便可以用該功能來實作。
效果圖:
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuEmMzM2NiZjY2ITOilTM3ITOhJGO1E2NzcjY2gDNwETNfdWbp9CXt92Yu4GZjlGbh5SZslmZxl3Lc9CX6MHc0RHaiojIsJye.png)
點選【Upload】按鈕,上傳檔案到資料庫;
點選【Preview】,預覽檔案;
具體實作:
前台:
1 <tr>
2 <td class="subject" nowrap="nowrap" align="right" style="width: 180px; text-align: right;"><%=Resources.WebResource.OE_ID_TYPE%>
3 <!--ID Type-->
4 :
5 </td>
6 <td style="color: #F90;">
7 <asp:DropDownList ID="drpIDType_N" runat="server" style="width: 25%;" OnSelectedIndexChanged="drpIDType_N_SelectedIndexChanged" AutoPostBack="true"></asp:DropDownList>
8 <span style="color: Red;">*</span>
9 <asp:FileUpload ID="btnFile" runat="server" Style="width: 25%;" />
10
11 <input type="button" id="btnUpload" runat="server" value='<%$ Resources:WebResource,CC_UPLOAD%>' onserverclick="btnUpload_Click" Visible="true" style="height:inherit; text-align: center;color: #b44c00;font-weight: 700;background-color: #ffe926;" />
12 <a href="Javascript: void(0)" id="lnkShowImg" runat="server" title="<%$ Resources:WebResource,IMG_PREVIEW_TITLE%>" visible="false" style="width:15%"><%=Resources.WebResource.IMG_PREVIEW%></a>
13 </td>
14 </tr>
15 <tr>
16 <td class="subject" nowrap="nowrap" align="right" style="width: 180px; text-align: right;"><%=Resources.WebResource.OE_ID_NO%>
17 <!--ID No-->
18 :
19 </td>
20 <td class="name">
21 <input type="text" runat="server" id="txtIDNO_N" maxlength="50" style="width: 96.6%;" />
22 <span style="color: Red">*</span>
23 </td>
24 </tr>
View Code
背景:
1 protected void btnUpload_Click(object sender, EventArgs e)
2 {
3 try
4 {
5 UploadImg(this.btnFile, this.txtEmployeeID, this.txtDEPID);
6 }
7 catch (Exception ex)
8 {
9 ShowError("W99999", "J00006", o_PopupWin, this.mLanguage);
10 WriteLog(ex.ToString());
11 WriteLog("Browser:" + HttpContext.Current.Request.Browser.Browser);
12 }
13 }
14
15 private void UploadImg(FileUpload file, string s_EmployeeID, string s_DEPID)
16 {
17 //驗證檔案類型
18 Boolean fileOK = false;
19 String fileExtension;
20 if (file.HasFile) //判斷是否有圖檔上來了
21 {
22 fileExtension = System.IO.Path.GetExtension(file.FileName.Trim()).ToLower();//擷取檔案擴充名
23 String[] allowedExtensions = { ".jpg", ".png", ".jpeg" }; //允許上傳的檔案格式
24 for (int i = 0; i < allowedExtensions.Length; i++)
25 {
26 if (fileExtension == allowedExtensions[i])
27 {
28 fileOK = true;
29 break;
30 }
31 }
32 }
33 else
34 {
35 Response.Write("<script>alert('進行提示');</script>");
36 return;
37 }
38 if (!fileOK)
39 {
40 Response.Write("<script>alert('進行提示');</script>");
41 return;
42 }
43
44 #region 因浏覽器相容問題,會取不到檔案完整路徑,是以先将檔案儲存到本地
45 string strFileLocalPath = Server.MapPath("../../Upload//Tmp//");
46 string strFileName = strFileLocalPath + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExtension;
47 if (Directory.Exists(strFileLocalPath) == false)
48 {
49 Directory.CreateDirectory(strFileLocalPath);
50 }
51 if (file.PostedFile.FileName.Trim() != "")
52 {
53 file.PostedFile.SaveAs(strFileName);
54 WriteLog("Browser:" + HttpContext.Current.Request.Browser.Browser);
55 }
56 #endregion
57
58 //将檔案讀進二進制記憶體
59 byte[] photo = Utility.getImg(strFileName, true);
60
61 //插入資料庫
62 o_CC_Insured_BLL.insertOrUpdateCCImg(fileExtension, System.IO.Path.GetFileName(file.PostedFile.FileName), photo);
63
64 //給【Preview】賦JS事件
65 setShowImgLink(s_EmployeeID, s_DEPID);
66
67 //提示上傳成功
68 ShowOk("W00058", "J00005", o_PopupWin, this.mLanguage);
69 }
70
71 /// <summary>
72 /// 從資料庫裡面查詢已上傳的檔案
73 /// </summary>
74 /// <param name="filePath"></param>
75 /// <returns></returns>
76 private void setShowImgLink(string s_EmployeeID, string s_DEPID)
77 {
78 DataTable dtimg = new DataTable();
79
80 dtimg = o_CC_Insured_BLL.getUploadFileCC(s_EmployeeID, s_DEPID);
81 if (dtimg.Rows.Count > 0)
82 {
83 lnkShowImg.Attributes.Add("onclick", "funOpenShowImage('" + s_EmployeeID + "','" + s_DEPID + "');");
84 lnkShowImg.Visible = true;
85 }
86 else
87 {
88 lnkShowImg.Visible = false;
89 }
90 }
91
92 /// <summary>
93 /// 将圖檔檔案寫入二進制對象
94 /// </summary>
95 /// <param name="filePath"></param>
96 /// <returns></returns>
97 public static byte[] getImg(string filePath, bool deleteFlg)
98 {
99 //讀取圖檔
100 FileStream fs = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read);
101 BinaryReader br = new BinaryReader(fs);
102 byte[] photo;
103 try
104 {
105 photo = br.ReadBytes((int)fs.Length);
106 }
107 finally
108 {
109 br.Close();
110 fs.Close();
111 }
112 //删除檔案
113 if (deleteFlg)
114 {
115 //删除圖檔檔案
116 if (File.Exists(filePath))
117 {
118 File.Delete(filePath);
119 }
120 }
121 return photo;
122 }
JS:
1 function funOpenShowImage(s_EmployeeID, s_DEPID) {
2 var strUrl = "../showUploadImg.aspx";
3 if (document.all)//IE浏覽器
4 {
5 var strParm = s_EmployeeID + "," + s_DEPID
6 openNewWin_IE(strUrl, strParm, 850, 630, "newwin");
7 }
8 else if ((/Trident\/7\./).test(navigator.userAgent))//IE11浏覽器
9 {
10 var strParm = s_EmployeeID + "," + s_DEPID
11 openNewWin_IE11(strUrl, strParm, 850, 630, "newwin");
12 }
13 else//其他浏覽器
14 {
15 var aryParm = [["EmployeeID", s_EmployeeID], ["DEPID", s_DEPID]];
16 OpenNewWin(strUrl, aryParm, 850, 630, "newwin");
17 }
18 }
預覽需要建立一個頁面:
建立showUploadImg.aspx
添加Img控件
1 <div>
2 <img runat="server" id="imgShow" src="\Upload\TMP\aaa.jpg" />
3 </div>
1 protected void Page_Load(object sender, EventArgs e)
2 {
3 try
4 {
5 clearTmp(Server.MapPath("../Upload/TMP/"));
6 //setInsured();
7 //saveImg();
8
9 string _EmployeeID = string.Empty;
10 string _DepID = string.Empty;
11 string strParm = this.Request.Form.Get("param") == null ? "" : Server.HtmlDecode(this.Request.Form.Get("param"));
12 if (string.IsNullOrEmpty(strParm))
13 {
14 _EmployeeID = this.Request.Form.Get("EmployeeID") == null ? "" : Server.HtmlDecode(this.Request.Form.Get("EmployeeID"));
15 _DepID = this.Request.Form.Get("DEPID") == null ? "" : Server.HtmlDecode(this.Request.Form.Get("DEPID"));
16 }
17 else
18 {
19 string[] arrParm = strParm.Split(',');
20 _EmployeeID = arrParm[0] == null ? "" : arrParm[0];
21 _DepID = arrParm[1] == null ? "" : arrParm[1];
22 }
23
24 //從資料庫讀取檔案
25 DataTable dtImg = new DataTable();
26 dtImg = o_CC_Insured_Bll.getUploadFileCC(_EmployeeID, _DepID);
27
28 string strFileName = _EmployeeID + DateTime.Now.ToString("yyyyMMddhhmmss") + ".JPG";
29 string strPhotoPath = "../Upload/TMP/";
30 string strFullPhotoPath = Server.MapPath(strPhotoPath) + strFileName;
31 if (dtImg.Rows.Count > 0 && dtImg.Rows[0]["ImgFile"] != DBNull.Value)
32 {
33 if (Directory.Exists(Server.MapPath(strPhotoPath)) == false)
34 {
35 Directory.CreateDirectory(Server.MapPath(strPhotoPath));
36 }
37 string setImgResult = setImg((byte[])dtImg.Rows[0]["ImgFile"], strFullPhotoPath);
38 if (string.IsNullOrEmpty(setImgResult))
39 {
40 imgShow.Src = strPhotoPath + strFileName;
41 }
42 }
43 }
44 catch
45 {
46 ShowError("W99999", "J00006", o_PopupWin, this.mLanguage);
47 }
48 }
49
50
51 /// <summary>
52 /// 清空檔案夾下的内容
53 /// </summary>
54 /// <param name="folderPath"></param>
55 public static void clearTmp(string folderPath)
56 {
57 //判斷是否有這樣的路徑
58 if (System.IO.Directory.Exists(folderPath) == true)
59 {
60 DirectoryInfo theFolder = new DirectoryInfo(folderPath);
61 FileInfo[] fileInfo = theFolder.GetFiles();
62 foreach (FileInfo NextFile in fileInfo) //周遊檔案
63 {
64 try
65 {
66 File.Delete(NextFile.FullName);
67 }
68 catch { }
69 }
70 }
71 }
72 /// <summary>
73 /// 讀取圖檔檔案到指定目錄
74 /// </summary>
75 /// <param name="img"></param>
76 /// <param name="filePath"></param>
77 /// <returns></returns>
78 public static string setImg(byte[] img, string filePath)
79 {
80 try
81 {
82 BinaryWriter bw = new BinaryWriter(File.Open(filePath, FileMode.OpenOrCreate));
83 bw.Write(img);
84 bw.Close();
85 return "";
86 }
87 catch (Exception ex)
88 {
89 return ex.ToString();
90 }
91 }
JS開啟新視窗的共用方法:
1 //目的:提供開啟視窗的畫面
2 //參數:strUrl-->欲開啟畫面的網址,strParms-->參數,width-->畫面的寬度,height-->畫面的高度
3 // WinName-->開啟的視窗名稱
4 // xx. YYYY/MM/DD VER AUTHOR COMMENTS
5 // 1. 2016/08/22 1.00 Anne Create
6 function OpenNewWin(strUrl,aryParms,width,height,WinName)
7 {
8 var top=0;
9 var left=0;
10 if (height =='' && width==''){
11 width=screen.availWidth;
12 height=screen.availHeight;
13 }else if (height >screen.availHeight && width>screen.availWidth){
14 width=screen.availWidth;
15 height=screen.availHeight;
16 }else{
17 top=(screen.availHeight-height)/2;
18 left=(screen.availWidth-width)/2;
19 }
20 var newWindow = window.open("",WinName,'width='+width+'px,height='+height+'px,dependent,left='+left+',top='+top+',status=no,toolbar=false,menubar=no,scrollbars=yes,resizable=yes',true);
21 if (!newWindow) return false;
22
23 var html ="";
24 //參數的處理
25 //var aryParm=strParms.split("&");//有多少個參數
26 var i=0;
27 for(i=0;i<aryParms.length;i++)
28 {
29 //var aryParaTemp = aryParm[i].split("=");//每一個參數
30 var aryParaTemp = aryParms[i];
31 html += "<input type='hidden' name='" + aryParaTemp[0] + "' value='" + aryParaTemp[1] + "'/>";//參數字段
32 }
33 html = "<html><head></head><body><form id='formid' method='post' action='"+strUrl+"'>"+html;
34 html += "</form><scr"+"ipt type='text/javascript'>document.getElementById('formid').submit()</scr"+"ipt></body></html>";
35 //html += "</form><script type='text/javascript'>document.getElementById('formid').submit()</script></body></html>";
36 newWindow.document.write(html);//送出post數據
37 }
38
39 //目的:提供開啟視窗的畫面(跨域跳轉的話,用OpenNewWin方法,IE浏覽器不相容,故重寫一個)
40 //參數:strUrl-->欲開啟畫面的網址,strParms-->參數,width-->畫面的寬度,height-->畫面的高度
41 // WinName-->開啟的視窗名稱
42 function openNewWin_IE(strUrl,strParam,width,height,name)
43 {
44 var tempForm = document.createElement("form");
45 tempForm.id="tempForm1";
46 tempForm.method="post";
47 tempForm.action=strUrl;
48 tempForm.target=name;
49 var hideInput = document.createElement("input");
50 hideInput.type="hidden";
51 hideInput.name= "param"
52 hideInput.value= strParam;
53 tempForm.appendChild(hideInput);
54 tempForm.attachEvent("onsubmit",function(){funWinOpen("",width,height,name);});
55 document.body.appendChild(tempForm);
56 tempForm.fireEvent("onsubmit");
57 tempForm.submit();
58 document.body.removeChild(tempForm);
59 }
60 function openNewWin_IE11(strUrl,strParam,width,height,name)
61 {
62 var tempForm = document.createElement("form");
63 tempForm.id="tempForm1";
64 tempForm.method="post";
65 tempForm.action=strUrl;
66 tempForm.target=name;
67 var hideInput = document.createElement("input");
68 hideInput.type="hidden";
69 hideInput.name= "param"
70 hideInput.value= strParam;
71 tempForm.appendChild(hideInput);
72 tempForm.addEventListener("onsubmit",function(){funWinOpen("",width,height,name);});
73 document.body.appendChild(tempForm);
74 tempForm.submit();
75 document.body.removeChild(tempForm);
76 }
77 function funWinOpen(strUrl,width,height,WinName)
78 {
79 var top=0;
80 var left=0;
81 if (height =='' && width==''){
82 width=screen.availWidth;
83 height=screen.availHeight;
84 }else if (height >screen.availHeight && width>screen.availWidth){
85 width=screen.availWidth;
86 height=screen.availHeight;
87 }else{
88 top=(screen.availHeight-height)/2;
89 left=(screen.availWidth-width)/2;
90 }
91 var newWindow = window.open(strUrl,WinName,'width='+width+'px,height='+height+'px,dependent,left='+left+',top='+top+',status=no,toolbar=false,menubar=no,scrollbars=yes,resizable=yes',true);
92 }
預覽效果圖:
如果您看了本篇部落格,覺得對您有所收獲,請點選右下角的
[推薦]如果您想轉載本部落格,
請注明出處如果您對本文有意見或者建議,歡迎留言
感謝您的閱讀,請關注我的後續部落格