现在的位置: 首页 > 综合 > 正文

FileUpload上传文件同时将文件保存到指定文件夹(附带判断上传文件大小)

2014年01月04日 ⁄ 综合 ⁄ 共 1456字 ⁄ 字号 评论关闭

 /// <summary>
    /// 上传文件同时将文件保存到指定文件夹
    /// </summary>
    /// <returns></returns>
    private bool SaveFiles()
    {
        try
        {
            if (fileUp.PostedFile.ContentLength < 1024 || fileUp.PostedFile.ContentLength > 1048576)
            {
                Response.Write("<script>alert('上传文件不得小于1K或不得大于1M!')</script>");
                return false;
            }
            else
            {
                ///'遍历File表单元素
                HttpFileCollection files = HttpContext.Current.Request.Files;
                /// '状态信息
                System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
                strMsg.Append("上传的文件内容是:<hr color=red>");
                for (int iFile = 0; iFile < files.Count; iFile++)
                {
                    ///'检查文件扩展名字
                    HttpPostedFile postedFile = files[iFile];
                    string fileName, fileExtension;
                    fileName = System.IO.Path.GetFileName(postedFile.FileName);
                    if (fileName != "")
                    {
                        fileExtension = System.IO.Path.GetExtension(fileName);
                        strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br />");
                        strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br />");
                        strMsg.Append("上传文件的文件名:" + fileName + "<br />");
                        strMsg.Append("上传文件的扩展名:" + fileExtension + "<br /></hr>");
                        ///将上传文件保存到指定的文件夹
                        postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("UpFiles/") + fileName);
                    }
                }
                return true;
            }
        }
        catch (System.Exception ex)
        {
            Response.Write("<script>alert('" + ex.ToString() + "!')</script>");
            return false;
        }
    }

抱歉!评论已关闭.