ASP.NET中文件上传下载方法集合(2)

<?xml version="1.0" encoding="gb2312" ?>
<Application>   
    <FileUpLoad>
       <Format>.jpg|.gif|.png|.bmp</Format>
    </FileUpLoad>
</Application>

  这样我们就可以开始写我们的上传文件的方法了,如下:

public FileUpLoad UpLoadFile(HtmlInputFile InputFile,string filePath,string myfileName,bool isRandom)
        {

            FileUpLoad fp = new FileUpLoad();

string fileName,fileExtension;
            string saveName;

            //
            //建立上传对象
            //
            HttpPostedFile postedFile = InputFile.PostedFile;

fileName        = System.IO.Path.GetFileName(postedFile.FileName);
            fileExtension    = System.IO.Path.GetExtension(fileName);

            //
            //根据类型确定文件格式
            //
            AppConfig app = new AppConfig();
            string format = app.GetPath("FileUpLoad/Format");


            //
            //如果格式都不符合则返回
            //
            if(format.IndexOf(fileExtension)==-1)
            {
                throw new ApplicationException("上传数据格式不合法");
            }

            //
            //根据日期和随机数生成随机的文件名
            //
            if(myfileName != string.Empty)
            {
                fileName = myfileName;           
            }

if(isRandom)
            {
                Random objRand = new Random();
                System.DateTime date = DateTime.Now;
                //生成随机文件名
                saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString()

+ date.Second.ToString() + Convert.ToString(objRand.Next(99)*97 + 100);
                fileName = saveName + fileExtension;
            }

            string phyPath = HttpContext.Current.Request.MapPath(filePath);


            //判断路径是否存在,若不存在则创建路径
            DirectoryInfo upDir = new DirectoryInfo(phyPath);
            if(!upDir.Exists)
            {
                upDir.Create();
            }

//
            //保存文件
            //
            try
            {
                postedFile.SaveAs(phyPath + fileName);

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjfsdw.html