Copy codeThe Code is as follows:
Using System;
Using System. Data;
Using System. Configuration;
Using System. Collections;
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;
Public partial class _ Default: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
}
Protected void bt_upload_Click (object sender, EventArgs e)
{
Try
{
If (FileUpload1.PostedFile. FileName = "")
{
This. lb_info.Text = "select a file! ";
}
Else
{
String filepath = FileUpload1.PostedFile. FileName;
If (IsAllowedExtension (FileUpload1) = true)
{
String filename = filepath. Substring (filepath. LastIndexOf ("\") + 1 );
String serverpath = Server. MapPath ("images/") + filename;
FileUpload1.PostedFile. SaveAs (serverpath );
This. lb_info.Text = "Upload successful! ";
}
Else
{
This. lb_info.Text = "upload an image ";
}
}
}
Catch (Exception error)
{
This. lb_info.Text = "Upload error! Cause: "+ error. ToString ();
}
}
Public static bool IsAllowedExtension (FileUpload hifile)
{
System. IO. FileStream fs = new System. IO. FileStream (hifile. PostedFile. FileName, System. IO. FileMode. Open, System. IO. FileAccess. Read );
System. IO. BinaryReader r = new System. IO. BinaryReader (fs );
String fileclass = "";
Byte buffer;
Try
{
Buffer = r. ReadByte ();
Fileclass = buffer. ToString ();
Buffer = r. ReadByte ();
Fileclass + = buffer. ToString ();
}
Catch
{
}
R. Close ();
Fs. Close ();
If (fileclass = "255216" | fileclass = "7173") // The 255216 is jpg, 7173 is gif, 6677 is BMP, 13780 is PNG, and 7790 is exe, 8297 is rar
{
Return true;
}
Else
{
Return false;
}
}
}
Test passed ....