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

以前检测文件类型的方式是检测文件的后缀后,如下:

bool fileOK = false;
string path = Server.MapPath("~/fileupttxload/");
if (FileUpload1.HasFile)
...{
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
String[] allowedExtensions = ...{ ".gif", ".png", ".bmp", ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
...{
if (fileExtension == allowedExtensions[i])
...{
fileOK = true;
}
}
}
if (fileOK)
...{
try
...{
FileUpload1.SaveAs(path + FileUpload1.FileName);
LabMessage1.Text = "文件上传成功.";
LabMessage2.Text = "<b>原文件路径:</b>" + FileUpload1.PostedFile.FileName + "<br />" +
"<b>文件大小:</b>" + FileUpload1.PostedFile.ContentLength + "字节<br />" +
"<b>文件类型:</b>" + FileUpload1.PostedFile.ContentType + "<br />";
}
catch (Exception ex)
...{
LabMessage1.Text = "文件上传不成功.";
}
}
else
...{
LabMessage1.Text = "只能够上传图片文件.";
}
}

但这种方法不安全,因为其它文件改成图片的后缀名也一样能上传.最好的方法是读取文件头信息,判断文件是否真的是图片.

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;
using System.IO;


public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public enum FileExtension
    {
        JPG = 255216,
GIF = 7173,
BMP = 6677,
PNG = 13780,
DOC = 208207,
DOCX = 8075,
XLS = 208207,
XLSX = 8075,
JS = 239187,
SWF = 6787,
TXT = 7067,
MP3 = 7368,
WMA = 4838,
MID = 7784,
RAR = 8297,
ZIP = 8075,
XML = 6063,

  // 7790 exe dll,
        // 8297 rar
        // 6063 xml
        // 6033 html
        // 239187 aspx
        // 117115 cs
        // 119105 js
        // 210187 txt
        //255254 sql
    }

    public class FileValidation
    {
        public static bool IsAllowedExtension(FileUpload fu, FileExtension[] fileEx)
        {
            int fileLen = fu.PostedFile.ContentLength;
            byte[] imgArray = new byte[fileLen];
            fu.PostedFile.InputStream.Read(imgArray, 0, fileLen);
            MemoryStream ms = new MemoryStream(imgArray);
            System.IO.BinaryReader br = new System.IO.BinaryReader(ms);
            string fileclass = "";
            byte buffer;
            try
            {
                buffer = br.ReadByte();
                fileclass = buffer.ToString();
                buffer = br.ReadByte();
                fileclass += buffer.ToString();
            }
            catch
            {
            }
            br.Close();
            ms.Close();
            foreach (FileExtension fe in fileEx)
            {
                if (Int32.Parse(fileclass) == (int)fe)
                    return true;
            }
            return false;
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string filename = "";
        Boolean fileOK = false;
        if (FileUpload1.HasFile)
        {
            String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
            String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension == allowedExtensions[i])
                {
                    fileOK = true;
                }
            }
        }

        FileExtension[] fe = { FileExtension.BMP, FileExtension.GIF, FileExtension.JPG, FileExtension.PNG };
        if (fileOK && FileValidation.IsAllowedExtension(FileUpload1, fe))
        {
            string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
            filename = "Images/" + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;
            FileUpload1.PostedFile.SaveAs(Server.MapPath(filename));
        }
        else
        {
            Response.Write("<script>alert('只支持以下格式的图片\\rJPG,BMP,GIF,PNG!');</script>");
            return;
        }

    }
}

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值