ASP.NET上传判断类型,防止黑客上传非法文件

检测文件类型函数类:

 1using System;
 2using System.Collections.Generic;
 3using System.Web.UI.WebControls;
 4using System.IO; 
 5
 6namespace 0x001.Pack
 7{
 8    public enum FileExtension
 9    {
10        JPG = 255216,
11        GIF = 7173,
12        BMP = 6677,
13        PNG = 13780
14        // 255216 jpg;
15        // 7173 gif;
16        // 6677 bmp,
17        // 13780 png;
18        // 7790 exe dll,
19        // 8297 rar
20        // 6063 xml
21        // 6033 html
22        // 239187 aspx
23        // 117115 cs
24        // 119105 js
25        // 210187 txt
26        //255254 sql 
27    }
 
28
29    public class FileValidation
30    {
31        public static bool IsAllowedExtension(FileUpload fu, FileExtension[] fileEx)
32        {
33            int fileLen = fu.PostedFile.ContentLength;
34            byte[] imgArray = new byte[fileLen];
35            fu.PostedFile.InputStream.Read(imgArray, 0, fileLen);
36            MemoryStream ms = new MemoryStream(imgArray);
37            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
38            string fileclass = "";
39            byte buffer;
40            try
41            {
42                buffer = br.ReadByte();
43                fileclass = buffer.ToString();
44                buffer = br.ReadByte();
45                fileclass += buffer.ToString();
46            }

47            catch
48            {
49            }

50            br.Close();
51            ms.Close();
52            foreach (FileExtension fe in fileEx)
53            {
54                if (Int32.Parse(fileclass) == (int)fe)
55                    return true;
56            }

57            return false;
58        }

59    }

60}
 
61
62

 

上传事件判断上传类型:

 1protected void btnUpload_Click(object sender, EventArgs e)
 2{
 3     string filename = "";
 4     Boolean fileOK = false;
 5     if (FileUpload1.HasFile)
 6     {
 7         String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
 8         String[] allowedExtensions = ".gif"".png"".jpeg"".jpg" };
 9         for (int i = 0; i < allowedExtensions.Length; i++)
10         {
11             if (fileExtension == allowedExtensions[i])
12             {
13                 fileOK = true;
14             }

15         }

16     }
 
17
18     FileExtension[] fe = { FileExtension.BMP, FileExtension.GIF, FileExtension.JPG, FileExtension.PNG };
19     if (fileOK && FileValidation.IsAllowedExtension(FileUpload1, fe))
20     {
21         string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
22         filename = "/Images/" + DateTime.Now.ToString("yyyyMMddHHmmss"+ fileExt;
23         FileUpload1.PostedFile.SaveAs(Server.MapPath(filename));
24     }

25     else
26     {
27        LTP.Common.MessageBox.Show(this"只支持以下格式的图片\\rJPG,BMP,GIF,PNG");
28        return;
29     }

30}
 
31
32

posted on 2009-03-30 10:16  Ljun  阅读(688)  评论(0编辑  收藏  举报

导航