- <html xmlns="http://www.w3.org/1999/xhtml">
- <head id="Head1" runat="server">
- <title>Untitled Page</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <asp:FileUpload ID="FileUpload1" runat="server" />
- <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
- <asp:Image ID="Image1" runat="server" />
- </form>
- </body>
- </html>
- using System;
- using System.Data;
- using System.Configuration;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- using System.Text;
- using System.IO;
- using System.Data.OleDb;
- public partial class Default2 : System.Web.UI.Page
- {
- private readonly string[] AcceptedFileTypes = new string[] { "jpg", "jpeg", "jpe", "gif", "bmp", "png" };
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- public string GetPicturePath()
- {
- string savePath = string.Empty;
- string strFileName = FileUpload1.PostedFile.FileName;
- if (string.IsNullOrEmpty(strFileName))
- {
- return string.Empty;
- }
- else
- {
- int intIndex = strFileName.LastIndexOf("//");
- string myFileName = strFileName.Substring(intIndex + 1);
- savePath = HttpContext.Current.Server.MapPath("~/HeadImage") + "//" + myFileName;
- FileUpload1.PostedFile.SaveAs(savePath);
- string mypath = "~/HeadImage" + "//" + myFileName;
- return mypath;
- }
- }
- protected void Button1_Click(object sender, EventArgs e)
- {
- if (CheckPicture())
- {
- Image1.ImageUrl = GetPicturePath();
- }
- }
- protected bool CheckPicture()
- {
- string strFileName = FileUpload1.PostedFile.FileName.ToLower();
- if (string.IsNullOrEmpty(strFileName))
- {
- Page.ClientScript.RegisterStartupScript(GetType(), "JS", "<script>alert('不能上傳空文件,請重新選擇!');</script>");
- return false;
- }
- else
- {
- string strtype = strFileName.Substring(strFileName.LastIndexOf(".") + 1, strFileName.Length - strFileName.LastIndexOf(".") - 1);
- for (int i = 0; i < AcceptedFileTypes.Length; i++)
- {
- if (strtype == AcceptedFileTypes[i])
- {
- return true;
- }
- }
- Page.ClientScript.RegisterStartupScript(GetType(), "JS", "<script>alert('上傳文件類型不符合要求,請重新選擇!');</script>");
- return false;
- }
- }
- }