asp.net上传代码

#region 判断上传文件类型
        private static  bool IsAllowableFileType(FileUpload FileUp)
        {
            //从web.config读取判断文件类型限制
            string strFileTypeLimit = ConfigurationManager.AppSettings["FileType"].ToString();
            //当前文件扩展名是否包含在这个字符串中
            if (strFileTypeLimit.IndexOf(Path.GetExtension(FileUp.FileName).ToLower()) != -1)
            {
                return true;
            }
            else
                return false;
        }
        #endregion
        #region 判断文件大小限制
        private static bool IsAllowableFileSize(FileUpload FileUp)
        {
            //从web.config读取判断文件大小的限制
            double iFileSizeLimit = Convert.ToInt32(ConfigurationManager.AppSettings["FileSizeLimit"]) * 1024;
            //判断文件是否超出了限制
            if (iFileSizeLimit > FileUp.PostedFile.ContentLength)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #endregion
        public static string UpLoad(ref FileUpload FileUp, string NewName)
        {
            string result = "";
            if (FileUp.PostedFile.ContentLength > 0)
            {
                if (IsAllowableFileType(FileUp))
                {
                    string UploadFilePath = ConfigurationManager.AppSettings["UploadFile"].ToString();
                    if (Directory.Exists(UploadFilePath) == false)//判断文件夹是否存在,若不存在则创建
                    {
                        Directory.CreateDirectory(UploadFilePath);
                    }
                    else
                        if (IsAllowableFileSize(FileUp))
                        {
                            UploadFilePath = UploadFilePath +"\\"+ NewName;
                            FileUp.SaveAs(UploadFilePath);
                            result = "ok," + (UploadFilePath);
                        }
                        else
                        {
                            result = "文件大小超过限制!,";
                        }
                }
                else
                {
                    result = "文件类型错误!,";
                }
            }
            else
            {
                result = "请选择文件!,";
            }
            return result;
        }
    }
    <add key="FileType" value=".xls"/>
    <add key="FileSizeLimit" value="102400"/>
    <add key="UploadFile" value="D:\UpLoad"/>
posted @ 2012-04-23 14:44  旋转之刃  阅读(153)  评论(0编辑  收藏  举报