欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net C#实现下载文件的六种方法实例

程序员文章站 2024-03-02 09:06:25
复制代码 代码如下:protected void button1_click(object sender, eventargs e)  {  /*&nb...

复制代码 代码如下:

protected void button1_click(object sender, eventargs e)
  {
  /*
  微软为response对象提供了一个新的方法transmitfile来解决使用response.binarywrite
  下载超过400mb的文件时导致aspnet_wp.exe进程回收而无法成功下载的问题。
  代码如下:
  */

  response.contenttype = "application/x-zip-compressed";
  response.addheader("content-disposition", "attachment;filename=z.zip");
  string filename = server.mappath("download/aaa.zip");
  response.transmitfile(filename);
  }

  //writefile实现下载
  protected void button2_click(object sender, eventargs e)
  {
  /*
  using system.io;

  */

  string filename ="aaa.zip";//客户端保存的文件名
  string filepath=server.mappath("download/aaa.zip");//路径

  fileinfo fileinfo = new fileinfo(filepath);
  response.clear();
  response.clearcontent();
  response.clearheaders();
  response.addheader("content-disposition", "attachment;filename=" + filename);
  response.addheader("content-length", fileinfo.length.tostring());
  response.addheader("content-transfer-encoding", "binary");
  response.contenttype = "application/octet-stream";
  response.contentencoding = system.text.encoding.getencoding("gb2312");
  response.writefile(fileinfo.fullname);
  response.flush();
  response.end();
  }

  //writefile分块下载
  protected void button3_click(object sender, eventargs e)
  {

  string filename = "aaa.zip";//客户端保存的文件名
  string filepath = server.mappath("download/aaa.zip");//路径

  system.io.fileinfo fileinfo = new system.io.fileinfo(filepath);

  if (fileinfo.exists == true)
  {
  const long chunksize = 102400;//100k 每次读取文件,只读取100k,这样可以缓解服务器的压力
  byte[] buffer = new byte[chunksize];

  response.clear();
  system.io.filestream istream = system.io.file.openread(filepath);
  long datalengthtoread = istream.length;//获取下载的文件总大小
  response.contenttype = "application/octet-stream";
  response.addheader("content-disposition", "attachment; filename=" + httputility.urlencode(filename));
  while (datalengthtoread > 0 && response.isclientconnected)
  {
  int lengthread = istream.read(buffer, 0, convert.toint32(chunksize));//读取的大小
  response.outputstream.write(buffer, 0, lengthread);
  response.flush();
  datalengthtoread = datalengthtoread - lengthread;
  }
  response.close();
  }
  }

  //流方式下载
  protected void button4_click(object sender, eventargs e)
  {
  string filename = "aaa.zip";//客户端保存的文件名
  string filepath = server.mappath("download/aaa.zip");//路径

  //以字符流的形式下载文件
  filestream fs = new filestream(filepath, filemode.open);
  byte[] bytes = new byte[(int)fs.length];
  fs.read(bytes, 0, bytes.length);
  fs.close();
  response.contenttype = "application/octet-stream";
  //通知浏览器下载文件而不是打开
  response.addheader("content-disposition", "attachment; filename=" + httputility.urlencode(filename, system.text.encoding.utf8));
  response.binarywrite(bytes);
  response.flush();
  response.end();

  }