游戏技术文章

ASP.NET网页中RAR、DOC、PDF等文件下载功能实例源代码

时间:2017-1-8 21:27:22  作者:棋牌资源网  来源:棋牌资源网  查看:6576  评论:0
内容摘要:以前做asp.net下载功能的时候都是采用:下载的方式来实现下载。但后来发现,这种方法存在诸多弊端。至于弊端原因百度一下就明白了。所以,下面分享下自...
以前做asp.net下载功能的时候都是采用:

<a href="http://www.wang0214.com/wgcms">下载</a>
的方式来实现下载。

但后来发现,这种方法存在诸多弊端。至于弊端原因百度一下就明白了。

所以,下面分享下自己修改完善后,asp.net加密文件下载功能:

 

不想看详细介绍的直接点击这里下载:
开始下载:点击下载
解压密码:www.wang0214.com


1、首先新建一个用于进行下载处理的page页,如download.aspx,里面不需要写任何东西。

 

2、新建一个DownloadHandler类,它继承于IHttpHandler接口,可以用来自定义HTTP 处理程序同步处理HTTP的请求。

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.IO;

/// <summary>
///DownloadHandler 的摘要说明
///万广互联(www.wang0214.com)
///专业品牌网站建设
/// </summary>
public class DownloadHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        HttpResponse Response = context.Response;
        HttpRequest Request = context.Request;
        System.IO.Stream iStream = null;
        byte[] buffer = new Byte[10240];
        int length;
        long dataToRead;
        try
        {
            string filename = FileHelper.Decrypt(Request["fn"]); //通过解密得到文件名
            string filepath = HttpContext.Current.Server.MapPath("~/") + "files/" + filename; //待下载的文件路径
            iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
            System.IO.FileAccess.Read, System.IO.FileShare.Read);
            Response.Clear();
            dataToRead = iStream.Length;
            long p = 0;
            if (Request.Headers["Range"] != null)
            {
                Response.StatusCode = 206;
                p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
            }
            if (p != 0)
            {
                Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
            }
            Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());
            Response.ContentType = "application/octet-stream";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(filename))));
            iStream.Position = p;
            dataToRead = dataToRead - p;
            while (dataToRead > 0)
            {
                if (Response.IsClientConnected)
                {
                    length = iStream.Read(buffer, 0, 10240);
                    Response.OutputStream.Write(buffer, 0, length);
                    Response.Flush();
                    buffer = new Byte[10240];
                    dataToRead = dataToRead - length;
                }
                else
                {
                    dataToRead = -1;
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write("Error : " + ex.Message);
        }
        finally
        {
            if (iStream != null)
            {
                iStream.Close();
            }
            Response.End();
        }
    }
    public bool IsReusable
    {
        get { return true; }
    }
}

3、这里涉及到一个文件名加解密的问题,是为了防止文件具体名称暴露在状态栏中,所以添加一个FileHelper类,代码如下:

using System;
using System.Collections.Generic;
using System.Web;

/// <summary>
///FileHelper 的摘要说明
/// </summary>
public class FileHelper
{
    public static string Encrypt(string filename)
    {
        byte[] buffer = HttpContext.Current.Request.ContentEncoding.GetBytes(filename);
        return HttpUtility.UrlEncode(Convert.ToBase64String(buffer));
    }
    public static string Decrypt(string encryptfilename)
    {
        byte[] buffer = Convert.FromBase64String(encryptfilename);
        return HttpContext.Current.Request.ContentEncoding.GetString(buffer);
    }
}

4、在Web.config上,添加httpHandlers结点,如下:

<system.web>
      <httpHandlers>
        <add verb="*" path="download.aspx" type="DownloadHandler" />
      </httpHandlers>
</system.web>

5、现在新建一个aspx页面,对文件进行下载:
Default.aspx代码如下: 
Default.aspx Code

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>文件下载</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:HyperLink ID="link" runat="server" Text="文件下载"></asp:HyperLink>
</div>
</form>
</body> 
</html>

Default.aspx.cs代码如下: 
Default.aspx.cs Code

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;

public partial class _Default : System.Web.UI.Page 
{    
    //全局变量
    private static object _SyncLockObject = new object();

    protected void Page_Load(object sender, EventArgs e)
    {
        string url = FileHelper.Encrypt("万广互联_深圳网站建设.jpg");
        link.NavigateUrl = "~/download.aspx?fn=" + url; 
    }
}

标签:ASP.NET网页中RAR、DOC、PDF等文件下载功能实例源代码 

欢迎加入VIP,【VIP售价:只要288元永久VIP会员】畅享商业棋牌游戏程序下载,点击开通!

下载说明


☉本站所有源码和资源均由站长亲自测试-绝对保证都可以架设,运营!
☉如源码和资源有损坏或所有链接均不能下载,请告知管理员,

☉本站软件和源码大部分为站长独资,资源购买和收集,放心下载!

☉唯一站长QQ:1004003180  [人格担保-本站注重诚信!]

☉购买建议E-mail:1004003180@qq.com   源码收购 E-mail:1004003180@qq.com    

☉本站文件解压密码  【文章内都自带解压密码,每个密码不同!】


本站提供的所有源码,均来源站长提供,仅学习交流 浙ICP备09009969号

由此产生不良后果和法律责任与本站无关,如果侵犯了您的版权,请来信告知 1004003180@qq.com 将及时更正和删除! 

Copyright © 2008-2022 棋牌资源网,你身边的棋牌资源下载站    All Rights Reserved