多文件上传方法

1.js代码 

function uploadFile() {
            var str = '<br/><INPUT type="file" size="30" NAME="File">'
            document.getElementById('MyFile').insertAdjacentHTML("beforeEnd", str)
        }

 

2.页面含义html代码(页面必须含有一个runat=“server”的file对象)

   <p id="MyFile"> <input type="file" size="30" name="File" runat="server"></p> <input type="button" value="增加(Add)" onclick="uploadFile()">

3.后台页面代码

   public bool attachfileupload()
        {
            Hashtable ht = new Hashtable();
            HttpFileCollection files = HttpContext.Current.Request.Files;
            for (int iFile = 0; iFile < files.Count; iFile++)
            {
                HttpPostedFile postedFile = files[iFile];
                string filePathName = postedFile.FileName;
                string fileName = Path.GetFileName(filePathName);
                string fileExtension = Path.GetExtension(filePathName);
                if (fileExtension == ".jpg" || fileExtension == ".bmp" || fileExtension == ".gif" || fileExtension == ".png" || fileExtension == ".txt" || fileExtension == ".docx" || fileExtension == ".doc" || fileExtension == ".xls" || fileExtension == ".rar")
                {
                }
                else
                {
                    ClientScript.RegisterStartupScript(Page.GetType(), "filetype", "alert('"+filePathName+"类型错误,请选择正确的文件类型')", true);
                    return false;
                }
            }
            //文件类型正确
            //文件大小
            for (int iFile = 0; iFile < files.Count; iFile++)
            {
                HttpPostedFile postedFile = files[iFile];
                string filePathName = postedFile.FileName;
                string fileName = Path.GetFileName(filePathName);
                string fileExtension = Path.GetExtension(filePathName);
                if (postedFile.ContentLength < 5120000)
                {
                }
                else
                {
                    ClientScript.RegisterStartupScript(typeof(string), "filetye", "alert('"+filePathName+"文件大小超出范围')", true);
                    return false;
                }
            }
            //上传文件
            for (int iFile = 0; iFile < files.Count; iFile++)
            {
                HttpPostedFile postedFile = files[iFile];
                string filePathName = postedFile.FileName;
                string fileName = Path.GetFileName(filePathName);
                string fileExtension = Path.GetExtension(filePathName);
                string fileid = System.Guid.NewGuid().ToString()  + fileExtension;

                postedFile.SaveAs(Server.MapPath(@"~/upload/" + fileid));

            }

 

 

                    

posted @ 2013-07-29 11:44  returnKing  阅读(320)  评论(0编辑  收藏  举报