Asp. NET code for advanced judgment of file types when uploading files-practical tips

Source: Internet
Author: User
Copy Code code 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 = "Please 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 success!" ";
}
Else
{
This.lb_info. Text = "please upload pictures";
}
}
}
catch (Exception error)
{
This.lb_info. Text = "Upload Error!" Reason: "+ 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")//Description 255216 is jpg;7173 is gif;6677 is bmp,13780 is png;7790 is exe,8297 is rar
{
return true;
}
Else
{
return false;
}
}
}

Test pass ....

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.