小文件上传代码

 

前台:

<input type="file" runat="server" id="oFile" /><a runat="server" onclick="if(document.getElementById('oFile').value==''){alert('请先选择文件!');return false;}" onserverclick="Upfile_Click" href="#">上传图片</a>

后台:

        protected void Upfile_Click(object sender, EventArgs e)
        {
            HttpPostedFile hpf = oFile.PostedFile;
            if (hpf.ContentLength > 3 * 1024 * 1024)
            {
                MsgShow("很抱歉,上传的图片不能超过3M!");
                return;
            }
            string extOnly="jpg|png|bmp|gif";
            if (!CheckExtValid(hpf.FileName, extOnly))
            {              
                MsgShow("文件类型限定为:" + extOnly.Replace("|", "、"));
                return;
            }

            //设置服务器文件路径
            string dFile = SiteConfig.ImgMap +"\\images\\upload\\"; 
            Sxmobi.FileHelper.EnsureDir(dFile);
           //dFile += Path.GetFileName(hpf.FileName); //原文件名
            dFile += DateTime.Now.ToString("yyyyMMddHHmmssfff")+ Path.GetExtension(hpf.FileName);
            hpf.SaveAs(dFile);
            MsgShow("上传成功!");
        }

        bool CheckExtValid(string filename, string extOnly)
        {
            string strExt = Path.GetExtension(filename).ToUpper();
            bool bOK = true;
            if (extOnly != "")
            {
                bOK = false;
                string[] arrOnly = extOnly.Split('|');
                for (int i = 0; i < arrOnly.Length; i++)
                {
                    if (strExt == "." + arrOnly[i].ToUpper())
                        bOK = true;
                }
            }
            return bOK;
        }

        void MsgShow(string msg)
        {
            Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('" + msg + "')</script>");

        }

转载请注明出处:http://blog.csdn.net/dasihg/article/details/6793656

原文地址:https://www.cnblogs.com/dashi/p/4034777.html