C# 使用FileUpload控件上传图片,将文件转换成二进制进行存储与读取
2021-05-07 06:28
YPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
标签:htm ref form /tmp nal head remove local color
状况描述:
需要上传文件,但是不想要保存到实体路径下,便可以用该功能来实现。
效果图:
点击【Upload】按钮,上传文件到数据库;
点击【Preview】,预览文件;
具体实现:
前台:
12 15class="subject" nowrap="nowrap" align="right" style="width: 180px; text-align: right;"> 3 4 : 5 6"color: #F90;"> 7 14"drpIDType_N" runat="server" style="width: 25%;" OnSelectedIndexChanged="drpIDType_N_SelectedIndexChanged" AutoPostBack="true"> 8 "color: Red;">* 9 "btnFile" runat="server" Style="width: 25%;" /> 10 11 "button" id="btnUpload" runat="server" value=‘‘ onserverclick="btnUpload_Click" Visible="true" style="height:inherit; text-align: center;color: #b44c00;font-weight: 700;background-color: #ffe926;" /> 12 "Javascript: void(0)" id="lnkShowImg" runat="server" title="" visible="false" style="width:15%"> 13 16 class="subject" nowrap="nowrap" align="right" style="width: 180px; text-align: right;"> 17 18 : 19 20class="name"> 21 "text" runat="server" id="txtIDNO_N" maxlength="50" style="width: 96.6%;" /> 22 "color: Red">* 23 24
后台:
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 ) 25 { 26 if (fileExtension == allowedExtensions[i]) 27 { 28 fileOK = true; 29 break; 30 } 31 } 32 } 33 else 34 { 35 Response.Write(""); 36 return; 37 } 38 if (!fileOK) 39 { 40 Response.Write(""); 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 ///72 /// 从数据库里面查询已上传的文件 73 /// 74 /// 75 /// 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 /// 93 /// 将图片文件写入二进制对象 94 /// 95 /// 96 /// 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控件
12 "server" id="imgShow" src="\Upload\TMP\aaa.jpg" /> 3
后台:
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 ///52 /// 清空文件夹下的内容 53 /// 54 /// 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 /// 73 /// 读取图片文件到指定目录 74 /// 75 /// 76 /// 77 /// 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) 28 { 29 //var aryParaTemp = aryParm[i].split("=");//每一個參數 30 var aryParaTemp = aryParms[i]; 31 html += "" + aryParaTemp[0] + "‘ value=‘" + aryParaTemp[1] + "‘/>";//參數字段 32 } 33 html = " "+"ipt type=‘text/javascript‘>document.getElementById(‘formid‘).submit() "+"ipt>"; 35 //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 } View Code
预览效果图:
C# 使用FileUpload控件上传图片,将文件转换成二进制进行存储与读取
标签:htm ref form /tmp nal head remove local color
原文地址:http://www.cnblogs.com/AnneHan/p/7646966.html
文章标题:C# 使用FileUpload控件上传图片,将文件转换成二进制进行存储与读取
文章链接:http://soscw.com/essay/83561.html