在项目中经常会遇到上传图片,在点击保存按钮向数据库提交数据之前,让图片显示在Image控件中,方法如下:
<tr> <td width="20%" align="right" class="tablesingletdlable"> <asp:Label ID="Label6" runat="server" Text="书图"></asp:Label> </td> <td align="left" width="80%" class="tablesingletdinput" colspan="3"> <asp:Image ID="tbtmpPic" runat="server" CssClass="inputc" Height="200px" Width="170px" /> <asp:HiddenField ID="allFileSize" runat="server" Value="0" /> <div id="msg" runat="server" style="text-align: center"> <fieldset> <legend>图 片 选 择 </legend>请选择图片:<asp:FileUpload ID="FileUpload1" runat="server" /> <a class="zInputBtn"> <asp:Button ID="btnConfirm" runat="server" Text="添加书籍图片" CssClass="inputButton" OnClick="btnConfirm_Click" /> </a> </fieldset> </div> </td> </tr> --------------------------------------------------- /// <summary> /// 图片选择确定 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnConfirm_Click(object sender, EventArgs e) { if (FileUpload1.HasFile) { string guid = Guid.NewGuid().ToString(); string newFileName = folder + "\\" + guid + Path.GetExtension(FileUpload1.FileName); url = Page.ResolveUrl("~") + "Admin/BookImages/" + guid + Path.GetExtension(FileUpload1.FileName); int totalFileSize = Int32.Parse(allFileSize.Value); int fileSize = FileUpload1.PostedFile.ContentLength; //此处也可以限制单个文件的大小 if (totalFileSize + fileSize > 1024 * 1024 * 100) { Page.ClientScript.RegisterClientScriptBlock(typeof(string), "", @"<script>alert('总上传的文件超过了大小设置 1024 * 1024 !')</script>"); return; } FileUpload1.SaveAs(newFileName); ListItem item = new ListItem(); item.Text = FileUpload1.FileName; item.Value = url + "|" + newFileName; tbtmpPic.Style["display"] = ""; tbtmpPic.ImageUrl = url; totalFileSize += fileSize; allFileSize.Value = totalFileSize.ToString(); } }