C# 使用FileUpload控件上传图片,将文件转换成二进制进行存储与读取
状况描述:
需要上传文件,但是不想要保存到实体路径下,便可以用该功能来实现。
效果图:
点击【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>
后台:
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 }
预览效果图:
作者:Anne Han
出处:https://www.cnblogs.com/AnneHan
GitHub:https://github.com/AnneHan
如果您看了本篇博客,觉得对您有所收获,请点击右下角的 [推荐]
如果您对本文有意见或者建议,欢迎留言
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。