Asp.net图片文件上传

本文介绍了一种优化的文件上传方案,包括使用GUID重命名文件、根据日期动态创建存储文件夹,并验证文件类型确保安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对课本上的代码进行了一点的优化

1.获取文件的名称和文件的后缀名

  引用了System.IO,

  用Path.GetFileNamehe()取得文件名和Path.GetExtension获取文件的后缀

2.对上传的文件进行了重命名

  采用Guid全局唯一标识进行命名

  Guid.NewGuid().ToString()

3.根据日期创建文件夹,先判断文件夹是否存在,不存在就创建一个

    创建文件夹:Directory.CreateDirectory(dir)

  string dir = "/Images/" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "/";

  判断文件夹是否存在

  Directory.Exists(Server.MapPath(dir))

  

 

protected void Button1_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile)
            {
                string fileName = Path.GetFileName(FileUpload1.FileName);

                //获取扩展名
                string fileExt = Path.GetExtension(fileName);

                if (fileExt == ".jpg")
                {
                    //对文件进行重命名,Guid全局唯一标识
                    string newFileName = Guid.NewGuid().ToString();

                    //创建文件夹
                    string dir = "/Images/" + DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day + "/";

                    //判断文件夹是否存在,不存在就创建一个
                    if (!Directory.Exists(Server.MapPath(dir)))
                    {
                        Directory.CreateDirectory(Server.MapPath(dir));
                    }
                    string fullDir = dir + newFileName + fileExt;

                    //上传到服务器
                    FileUpload1.SaveAs(Server.MapPath(fullDir));

                    this.Image1.ImageUrl = fullDir;

                    Response.Write("<script>alret('上传成功!!')</script>");

                }
                else
                {
                    Response.Write("<script>alert('请选择图片文件!')</script>");
                }
            }
            else
            {
                Response.Write("<script>alert('请选择上传文件!')</script>");
            }
        }

 

转载于:https://www.cnblogs.com/gx-143/p/6071473.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值