当前位置:中国站长下载文章中心网页编程.NET编程 → ASP.NET中文件上传下载方法集合(2)

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

减小字体 增大字体 作者:不详  来源:不详  发布时间:2006-8-14 8:34:08
     <?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);
  
    fp.FilePath = filePath + fileName;
    fp.FileExtension = fileExtension;
    fp.FileName = fileName;
   }
   catch
   {
    throw new ApplicationException("上传失败!");
   }
  
   //返回上传文件的信息
   return fp;
  }
  
    然后我们在上传文件的时候就可以调用这个方法了,将返回的文件信息保存到数据库中,至于下载,就直接打开那个路径就OK了。
  
    第三部分:
  
    这里我们主要说一下如何以二进制的形式上传文件以及下载。首先说上传,方法如下:
  
  public byte[] UpLoadFile(HtmlInputFile f_IFile)
  {
   //获取由客户端指定的上传文件的访问
   HttpPostedFile upFile=f_IFile.PostedFile;
   //得到上传文件的长度
   int upFileLength=upFile.ContentLength;
   //得到上传文件的客户端MIME类型
   string contentType = upFile.ContentType;
   byte[] FileArray=new Byte[upFileLength];
  
   Stream fileStream=upFile.InputStream;
  
   fileStream.Read(FileArray,0,upFileLength);
   return FileArray;
  }
  
    这个方法返回的就是上传的文件的二进制字节流,这样我们就可以将它保存到数据库了。下面说一下这种形式的下载,也许你会想到这种方式的下载就是新建一个 aspx页面,然后在它的Page_Load()事件里取出二进制字节流,然后再读出来就可以了,其实这种方法是不可取的,在实际的运用中也许会出现无法打开某站点的错误,我一般采用下面的方法:
  
    首先,在Web.config中加入:
  
  <add verb="*" path="openfile.aspx" type="RuixinOA.Web.BaseClass.OpenFile, RuixinOA.Web"/>
  
    这表示我打开openfile.aspx这个页面时,系统就会自动转到执行RuixinOA.Web.BaseClass.OpenFile 这个类里的方法,具体实现如下:
  
  using System;
  using System.Data;
  using System.Web;
  using System.IO;
  using Ruixin.WorkFlowDB;
  using RXSuite.Base;
  using RXSuite.Component;
  using RuixinOA.BusinessFacade;
  
  namespace RuixinOA.Web.BaseClass
  {
   /**//// <summary>
   /// NetUFile 的摘要说明。
   /// </summary>
   public class OpenFile : IHttpHandler
   {
    public void ProcessRequest(HttpContext context)
    {
     //从数据库中取出要下载的文件信息
     RuixinOA.BusinessFacade.RX_OA_FileManager os = new RX_OA_FileManager();
     EntityData data = os.GetFileDetail(id);
  
     if(data != null && data.Tables["RX_OA_File"].Rows.Count > 0)
     {
      DataRow dr = (DataRow)data.Tables["RX_OA_File"].Rows[0];
      context.Response.Buffer = true;
      context.Response.Clear();
      context.Response.ContentType = dr["CContentType"].ToString();
      context.Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(dr["CTitle"].ToString()));
      context.Response.BinaryWrite((Byte[])dr["CContent"]);
      context.Response.Flush();
      context.Response.End();
     }
    }
    public bool IsReusable
    {  
     get { return true;}
    }
   }
  }
  
    执行上面的方法后,系统会提示用户选择直接打开还是下载。这一部分我们就说到这里。
  
    第四部分:
  
    这一部分主要说如何上传一个Internet上的资源到服务器。
  
    首先需要引用 System.Net 这个命名空间,然后操作如下:
  
  HttpWebRequest hwq = (HttpWebRequest)WebRequest.Create("http://localhost/pwtest/webform1.aspx");
  HttpWebResponse hwr = (HttpWebResponse)hwq.GetResponse();
  byte[] bytes = new byte[hwr.ContentLength];
  Stream stream = hwr.GetResponseStream();
  stream.Read(bytes,0,Convert.ToInt32(hwr.ContentLength));
  //HttpContext.Current.Response.BinaryWrite(bytes);
  
    HttpWebRequest 可以从Internet上读取文件,因此可以很好的解决这个问题。
  
    第五部分:总结
  
    今天简单的介绍了几种文件上传与下载的方法,都是在实际的项目开发中经常需要用到的,可能还有不完善的地方,希望大家可以互相交流一下项目开发中的经验。  做人要厚道,请注明转自chinazhan中国站长(www.ChinaZhan.com)。