asp.net 使用FileUpload控制元件上傳並顯示圖片

暖楓無敵發表於2011-08-25

在專案中經常會遇到上傳圖片,在點選儲存按鈕向資料庫提交資料之前,讓圖片顯示在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();
        }
    }



相關文章