Slash

习惯在追逐的过程中不断去完善自己;当你不再去追逐,你自我完善的脚步也就停滞下来了。

导航

文件上传

实现图片文件上传至服务器端文件夹下,同时数据库中保存相应文件名便于存取,文件保存目录通过Web.config中设定。具体代码实现如下:
 1using System;
 2using System.IO;
 3
 4namespace fradmin.DBAccess
 5{
 6    /// <summary>
 7    /// File 的摘要说明。
 8    /// </summary>

 9    public class File
10    {
11        public File()
12        {
13            
14        }

15        //根据上传控件和上传属性选项返回完整上传图片的名称,产生按格式生成的文件名,同时传递保存目录参数
16        public string UpLoadImage(System.Web.UI.HtmlControls.HtmlInputFile upImage,string FilePath)
17        {
18            string strUpImage=upImage.Value.Trim();
19            //取对应的文件类型,扩展名
20            if(upImage.Value==null)
21                return null;
22            string strExtend=strUpImage.Substring(strUpImage.LastIndexOf(".")+1);
23            
24            //取得新文件名,通过取系统时间
25            string radFileName=DateTime.Now.ToString("yyyyMMddhhmmss")+RandomStr(5)+"."+strExtend;
26            
27            string upLoadPath=System.Web.HttpContext.Current.Server.MapPath(null)+"\\"+FilePath+radFileName;
28            //上传文件至相应路径
29            upImage.PostedFile.SaveAs(upLoadPath);
30            //返回值取存储在服务器上的完整文件名,便于数据库的插入操作记录,作为GoodImage字段值
31            return radFileName;
32        }

33        private string RandomStr(int Length)
34        {
35            Random rd=new Random();
36            string val=String.Empty;
37            for(int i=0;i<Length;i++)
38                val +=rd.Next(9).ToString();
39            return val;
40        }

41    }

42}

43
使用只需:
 1try
 2            {
 3                File upload=new File();
 4                fileName=upload.UpLoadImage(fileImage,ConfigurationSettings.AppSettings["ImageUrl"]);
 5            }

 6            catch
 7            {
 8                lblMessage.Text="图片上传出错";
 9                return;
10            }

posted on 2006-04-26 15:48  Slash  阅读(497)  评论(0编辑  收藏  举报