單一圖片上傳——“選擇”+“上傳”,.NET默認模式:
1.實現原理:
采用FileUpload控件默認的使用方式,先由“選擇”按鈕選擇圖片,然后單擊“上傳”按鈕完成上傳,並可在“上傳”按鈕的單擊事件中加載已上傳圖片。
2.關鍵代碼:
頁面代碼:
1 <asp:FileUpload ID="FileUpload" runat="server" /> 2 <asp:Button ID="BtnUp" runat="server" onclick="BtnUp_Click" Text="上 傳" /> 3 <asp:Label ID="LabMsg" runat="server"></asp:Label> 4 <img id="img" runat="server" src="" />
后台代碼:
1 /// <summary> 2 /// 上傳單一圖片——有“選擇”+“上傳”兩個按鈕 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 protected void BtnUp_Click(object sender, EventArgs e) 7 { 8 if (FileUpload.HasFile) 9 { 10 string savePath = Server.MapPath("~/upload/");//指定上傳文件在服務器上的保存路徑 11 //檢查服務器上是否存在這個物理路徑,如果不存在則創建 12 if (!System.IO.Directory.Exists(savePath)) 13 { 14 System.IO.Directory.CreateDirectory(savePath); 15 } 16 savePath = savePath + "\\" + FileUpload.FileName; 17 FileUpload.SaveAs(savePath); 18 LabMsg.Text = string.Format("<a href='upload/{0}'>upload/{0}</a>", FileUpload.FileName); 19 this.img.Src = "upload/" + FileUpload.FileName; 20 } 21 else 22 { 23 LabMsg.Text = "你還沒有選擇上傳文件!"; 24 } 25 }