C# 使用FileUpload控件上传图片,将文件转换成二进制进行存储与读取-阿里云开发者社区

开发者社区> annehan> 正文

C# 使用FileUpload控件上传图片,将文件转换成二进制进行存储与读取

简介: 状况描述:   需要上传文件,但是不想要保存到实体路径下,便可以用该功能来实现。   效果图:      点击【Upload】按钮,上传文件到数据库;   点击【Preview】,预览文件;   具体实现:   前台: 1 2 3 4 : 5 ...
+关注继续查看

状况描述:

  需要上传文件,但是不想要保存到实体路径下,便可以用该功能来实现。

 

效果图:

  

  点击【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 }
View Code

 

  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 }
View Code

 

  预览需要新建一个页面:

  新建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 }
View Code

 

  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 }
View Code

 

  预览效果图:

  

 

 

 

 

  

 

如果您看了本篇博客,觉得对您有所收获,请点击右下角的 [推荐]

如果您想转载本博客,请注明出处

如果您对本文有意见或者建议,欢迎留言

感谢您的阅读,请关注我的后续博客

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

相关文章
JQuery文件上传及以Base64字符串形式呈现图片
一:上传之 首先,你必然得有一个 file input,如下:         其次,让我们 upload,如下: $.ajaxFileUpload({     url: '@ViewBag.
550 0
CentOS 6.5安装二进制版本的MongoDB 2.6
CentOS 6.5安装二进制版本的MongoDB 2.6 MongoDB的国外镜像访问非常慢,以至于选择MongoDB官网的在线安装很不靠谱。那么,我们可以选择安装MongoDB 2.6的二进制发布包。
795 0
+关注
annehan
一个95后 一个程序媛
48
文章
0
问答
文章排行榜
最热
最新
相关电子书
更多
《2021云上架构与运维峰会演讲合集》
立即下载
《零基础CSS入门教程》
立即下载
《零基础HTML入门教程》
立即下载