首页 > 代码库 > C#文件授权下载
C#文件授权下载
1、创建HttpHandler
using System; using System.Collections.Generic; using System.Text; using System.Web; namespace Handler { public class DownloadHandler : IHttpHandler { public bool IsReusable { get { return true; } } public void ProcessRequest(HttpContext context) { //context.Response.Write(context.Request.Url.ToString()); context.Response.Write("<h1><b>您没有权限访问此文件,请联系网站管理员!</b></h1>"); context.Response.End(); } } }
2、配置iis,其中path处填写你要授权访问的文件类型,多个用‘,‘分割
<httpHandlers> <add verb="*" path="*.rar" type="Hander.DownloadHander, Hander"/> </httpHandlers>
3、在下载页面内添加如下方法
protected void Page_Load(object sender, EventArgs e) { //执行权限判断,如果拥有权限则执行下载 bool b = IsCanDown(); if (b) { string path = Request.QueryString["file"] != null ? Request.QueryString["file"] : "/upload/day_20140312/留言板.rar"; get_file(path); } } private bool IsCanDown() {
//处理逻辑 return true; } private void get_file(string path) { //string path = Request.QueryString["file"]; string filePath = Server.MapPath(path);//路径 string filename = Path.GetFileName(filePath); 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(); }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。