FileUpload实现图片的无重上传

        //如果确认了上传文件,则判断文件类型是否符合要求
        if (this.FileUpload1.HasFile)
        {
            //获取上传文件的后缀
            String fileExtension = System.IO.Path.GetExtension(this.FileUpload1.FileName).ToLower();
            String[] restrictExtension = { ".gif", ".jpg", ".bmp", ".png" };
            //判断文件类型是否符合要求
            for (int i = 0; i < restrictExtension.Length; i++)
            {
                if (fileExtension == restrictExtension[i])
                {
                    fileIsValid = true;
                }
            }
            //如果文件类型符合要求,调用SaveAs方法实现上传,并显示相关信息
            if (fileIsValid == true)
            {
                try
                {
                    String newname = Guid.NewGuid().ToString();//生成新的文件名,保证唯一性
                    this.Image1.ImageUrl = "~/images/head/" + newname+ FileUpload1.FileName;
                   
                    this.FileUpload1.SaveAs(Server.MapPath("~/images/head/") +newname+ FileUpload1.FileName);
                    this.Label1.Text = "文件上传成功";
                    this.Label1.Text += "<Br/>";
                    this.Label1.Text += "<li>" + "原文件路径:" + this.FileUpload1.PostedFile.FileName;
                    this.Label1.Text += "<Br/>";
                    this.Label1.Text += "<li>" + "文件大小:" + this.FileUpload1.PostedFile.ContentLength + "字节";
                    this.Label1.Text += "<Br/>";
                    this.Label1.Text += "<li>" + "文件类型:" + this.FileUpload1.PostedFile.ContentType;
                }
                catch (Exception ex)
                {
                    this.Label2.Text = "无法上传文件" + ex.Message;
                }
            }
            else
            {
                this.Label2.Text = "只能够上传后缀为.gif,.jpg,.bmp,.png的文件夹";
            }
        }

posted @ 2017-05-07 19:57  泊月居  阅读(587)  评论(0编辑  收藏  举报