WebForm的FileUpload控件实现选择完图片并直接上传

参考上一篇博客:https://www.cnblogs.com/xielong/p/15512372.html

在这上面的基础进行修改,要实现选择完图片并直接上传的效果

aspx前端代码

将上传图片按钮隐藏,通过js调用后端的btnUpload_Click方法

  <form id="form1" runat="server">
    <div>
        <div> 
            <asp:Image ID="imgShow" runat="server"  Style="background:#FFF;width:120px;height:100px;"  />
        </div>
        <div>
            <asp:FileUpload ID="fileSelect" runat="server"  accept="image/*" onchange="ExecBtnUpload(this)"  />   
        </div>
        <div style="display:none;">
            <asp:Button ID="btnUpload" runat="server" Text="上传图片" OnClick="btnUpload_Click" />
            <asp:Label ID="labTipMsg" runat="server" Style="color: Red"></asp:Label>  
        </div>
    </div>
    </form>

js调用方法(最重要的)

 <script>
         function ExecBtnUpload() {
          //模拟调用后台的上传图片方法(btnUpload_Click)
           window.document.getElementById('<%=btnUpload.ClientID %>').click();
       }
    </script>

aspx后端代码

   protected void btnUpload_Click(object sender, EventArgs e)
        {
            if (this.fileSelect.FileName == "")
            {
                this.labTipMsg.Text = "上传文件不能为空";
                return;
            }

            //如果确认了上传文件,则判断文件类型是否符合要求 
            if (this.fileSelect.HasFile)
            {
                //1、检查上传的文件路径是否存在
                //获取当前程序集的文件路径
                string applicationPath = AppDomain.CurrentDomain.BaseDirectory.ToString();
                //获取存放的文件夹名称
                string uploadfolder = ConfigurationManager.AppSettings["UploadImage"] == null ? "UploadImages" : ConfigurationManager.AppSettings["UploadImage"].ToString();
                //获取限制文件大小 MB
                int uploadSize = ConfigurationManager.AppSettings["UploadFileSize"] == null ? 4 : Convert.ToInt32(ConfigurationManager.AppSettings["UploadFileSize"]);
                //获取程序集路径+文件夹路径
                string toServerPath = applicationPath + "\\" + uploadfolder;
                //拼接上年月文件夹( C:\\UploadFiles\\201904 )
                toServerPath = toServerPath + "\\" + DateTime.Now.ToString("yyyyMM");
                //判断服务器文件夹路径是否存在
                if (!Directory.Exists(toServerPath))
                {
                    //不存在路径,则创建
                    Directory.CreateDirectory(toServerPath);
                }

                //获取上传文件的后缀 
                string fileExt = Path.GetExtension(this.fileSelect.FileName).ToLower();
                string[] fileExts = { ".jpg", ".jpeg", ".gif", ".png", ".bmp", ".ico" };
                //判断文件类型是否符合要求 
                if (fileExts.Contains(fileExt))
                {
                    //检查文件大小
                    if (fileSelect.PostedFile.ContentLength > (uploadSize * 1024 * 1024))
                    {
                        this.labTipMsg.Text = string.Format("上传文件超过最大限制{0}MB!", uploadSize);
                    }
                    else
                    {
                        try
                        {
                            //获取新文件名(包含后缀名),如:test_211104171831.jpg
                            string newFileName = this.fileSelect.FileName;  // "admin" + "_" + DateTime.Now.ToString("yyMMddHHmmss") + fileExt;
                            //获取绝对路径,如:D:\Project\Cpap\CpapWebForm\\UploadImages\202111\test_211104171831.jpg
                            string newFilePath = toServerPath + "\\" + newFileName;
                            //获取相对路径,如:\UploadImages\202111\test_211104171831.jpg
                            string relatePath = newFilePath.Substring(applicationPath.Length, newFilePath.Length - applicationPath.Length);
                            //拼接返回应用图片路径(将符号(\)替换成符号(/)), 如: ~/UploadImages/202111/test_211104171831.png
                            string appImgPath = "~" + relatePath.Replace('\\', '/');

                            //检查保存是否已存在,存在不做保存
                            if (!System.IO.File.Exists(newFilePath))
                            {
                                //3、保存上传的文件
                                this.fileSelect.SaveAs(newFilePath);
                            }                          
                            //显示图片  "~/UploadImage/" + FileUpload1.FileName;
                            this.imgShow.ImageUrl = appImgPath;

                            this.labTipMsg.Text = "上传文件成功!";
                        }
                        catch (Exception ex)
                        {
                            this.labTipMsg.Text = "上传文件失败,原因:" + ex.Message;
                        }

                    }
                }
                else
                {
                    this.labTipMsg.Text = "只能够上传后缀为.gif,.jpg,.bmp,.png的文件";
                }

            }
        }

运行后效果图

1)未选择图片

 2)选择后上传

 

 

3)项目保存图片路径

 

 

参考网址

https://blog.csdn.net/weixin_33907511/article/details/94348164

posted @ 2021-11-05 11:44  小小邪  阅读(300)  评论(0编辑  收藏  举报