ASPX文件上传限制类型实例源码

来源:岁月联盟 编辑:exp 时间:2012-08-15

小菜分享下自己的思路,不知道各位有木有更好的方法

源码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 //MyBlog:http://seay.sinaapp.com/
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        #region 文件类型判断
 
 //得到上传文件名
        string FileName = FileUpload1.FileName;
 
 //判断文件名中有木有.
        if (!(FileName.Contains(".")))
        {
            Response.Write("该文件类型不允许上传!");
            return;
        }
 
 //取到.的下标
        int index = FileName.LastIndexOf('.');

        char[] c = FileName.ToCharArray();

        string File_hz = "";
 
 //循环得到后缀名
        for (int i = 0; i < FileName.Length - index; i++)
        {
            File_hz += c[index + i];
        }

 //允许上传的文件名
        string[] FileType = { ".jpg", ".gif", ".bmp", ".jpeg" };

        bool bl = false;
 
 //循环遍历上传的文件扩展名是否在允许的扩展名中
        foreach (string str in FileType)
        {
            if (str == File_hz)
            {
                bl = true;
            }
        }

        if (bl == false)
        {
            Response.Write("该文件类型不允许上传!");
            return;
        }

        #endregion

        //获取时间戳给文件命名,这样写感觉有点复杂,不知道各位有木有好的方法获取时间戳
        DateTime starttime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
        DateTime newtime = DateTime.Now;

        long utime = (long)Math.Round((newtime - starttime).TotalMilliseconds, MidpointRounding.AwayFromZero);

        FileName = utime.ToString() + File_hz;

 //获取文件字节数
        string FileLenght = FileUpload1.PostedFile.ContentLength.ToString();
       
        string FilePath = Server.MapPath("img/" + FileName);
 
 //上传
        FileUpload1.SaveAs(FilePath);

        Response.Write("上传成功<br />文件大小:" + FileLenght + "<br />路径:img/" + FileName);
    }
}