PostBackTriggerCS.aspx 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <%@ Page Language="C#" %>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  3. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4. <script runat="server">
  5. private string saveDir = @"Uploads\";
  6. protected void UploadButton_Click(object sender, EventArgs e)
  7. {
  8. if (FileUpload1.HasFile && FileUpload1.FileBytes.Length < 10000 &&
  9. !CheckForFileName())
  10. {
  11. string savePath = Request.PhysicalApplicationPath + saveDir +
  12. Server.HtmlEncode(FileName.Text);
  13. //Remove comment from the next line to upload file.
  14. //FileUpload1.SaveAs(savePath);
  15. UploadStatusLabel.Text = "The file was processed successfully.";
  16. }
  17. else
  18. {
  19. UploadStatusLabel.Text = "You did not specify a file to upload, or a file name, or the file was too large. Please try again.";
  20. }
  21. }
  22. protected void CheckButton_Click(object sender, EventArgs e)
  23. {
  24. if (FileName.Text.Length > 0)
  25. {
  26. string s = CheckForFileName() ? "exists already." : "does not exist.";
  27. UploadStatusLabel.Text = "The file name choosen " + s;
  28. }
  29. else
  30. {
  31. UploadStatusLabel.Text = "Specify a file name to check.";
  32. }
  33. }
  34. private Boolean CheckForFileName()
  35. {
  36. System.IO.FileInfo fi = new System.IO.FileInfo(Request.PhysicalApplicationPath +
  37. saveDir + Server.HtmlEncode(FileName.Text));
  38. return fi.Exists;
  39. }
  40. </script>
  41. <html xmlns="http://www.w3.org/1999/xhtml" >
  42. <head runat="server">
  43. <title>PostBackTrigger Example</title>
  44. </head>
  45. <body>
  46. <form id="form1" runat="server">
  47. <div>
  48. <asp:ScriptManager ID="ScriptManager1" runat="server" />
  49. The upload button is defined as a PostBackTrigger.<br/>
  50. <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
  51. <ContentTemplate>
  52. <fieldset>
  53. <legend>FileUpload in an UpdatePanel</legend>
  54. First, enter a file name to upload your file to:
  55. <asp:TextBox ID="FileName" runat="server" />
  56. <asp:Button ID="CheckButton" Text="Check" runat="server" OnClick="CheckButton_Click" />
  57. <br />
  58. Then, browse and find the file to upload:
  59. <asp:FileUpload id="FileUpload1"
  60. runat="server">
  61. </asp:FileUpload>
  62. <br />
  63. <asp:Button id="UploadButton"
  64. Text="Upload file"
  65. OnClick="UploadButton_Click"
  66. runat="server">
  67. </asp:Button>
  68. <br />
  69. <asp:Label id="UploadStatusLabel"
  70. runat="server" style="color:red;">
  71. </asp:Label>
  72. </fieldset>
  73. </ContentTemplate>
  74. <Triggers>
  75. <asp:PostBackTrigger ControlID="UploadButton" />
  76. </Triggers>
  77. </asp:UpdatePanel>
  78. </div>
  79. </form>
  80. </body>
  81. </html>