您现在的位置是:网站首页> 编程资料编程资料

Asp.net利用一般处理程序实现文件下载功能_实用技巧_

2023-05-24 273人已围观

简介 Asp.net利用一般处理程序实现文件下载功能_实用技巧_

首先有一个html页面,页面有一个链接,点击链接弹出文件下载/保存(类似迅雷下载链接)

一般处理程序的代码如下

 using System.IO; using System.Web; namespace Zhong.Web { ///  /// DownloadFileHandler 的摘要说明 ///  public class DownloadFileHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { string filePath = context.Server.MapPath("~/App_Data/readme.txt"); FileStream fs = new FileStream(filePath, FileMode.Open); byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, bytes.Length); fs.Dispose(); context.Response.ContentType = "application/octet-stream"; context.Response.AddHeader("Content-Disposition", "attachment; filename=readme.txt"); context.Response.BinaryWrite(bytes); context.Response.Flush(); //大文件下载的解决方案 //context.Response.ContentType = "application/x-zip-compressed"; //context.Response.AddHeader("Content-Disposition", "attachment;filename=z.zip"); //string filename = Server.MapPath("~/App_Data/move.zip"); //context.Response.TransmitFile(filename); } public bool IsReusable { get { return false; } } } }

点击第一个链接访问,显示如下:

点击第二个链接访问,下载文件:

由于我之前已经测试过一次,所以这次下载时命名为readme(1).txt

-六神源码网