文件上传函数

     #region 文件上传函数
        /// <summary>
        /// 文件上传函数
        /// </summary>
        /// <param name="_savePath">虚拟路径 如../userFiles/</param>
        /// <returns></returns>
        public static List<string> UploadFile(string _savePath, FileUpload FileUpload1)
        {
            List<string> result = new List<string>(); //返回结果

            //if (FileUpload1.HasFile)
            //{
            try
            {
                string FileContentType = FileUpload1.PostedFile.ContentType;

                string ClientFileName = FileUpload1.PostedFile.FileName; //客户端文件路径(包含文件名)

                FileInfo ObjFileInfo = new FileInfo(ClientFileName);

                string FileName = ObjFileInfo.Name; //文件名

                _savePath = HttpContext.Current.Server.MapPath(_savePath);
                string webFileName = _savePath + FileName; //服务器端保存路径(包含文件名)


                if (!Directory.Exists(_savePath))
                {
                    Directory.CreateDirectory(_savePath);
                }


                if (!File.Exists(webFileName))
                {
                    try
                    {
                        FileUpload1.SaveAs(webFileName);
                        result.Add("文件上传成功");
                        result.Add(FileName);
                    }
                    catch (Exception ex)
                    {
                        result.Add(ex.Message);
                    }
                }
                else
                {
                    try
                    {
                        //覆盖原文件
                        FileUpload1.SaveAs(webFileName);
                        result.Add("文件已存在");
                        result.Add(FileName);
                    }
                    catch (Exception ex)
                    {
                        result.Add(ex.Message);
                    }
                }
            }
            catch(Exception ex)
            {
                result.Add(ex.Message);
            }
            //}
            return result;
        }
        #endregion

  

 

posted @ 2012-01-04 14:27  Damon201611  阅读(241)  评论(0编辑  收藏  举报