博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ASP.NET文件下载详细步骤
阅读量:5967 次
发布时间:2019-06-19

本文共 3523 字,大约阅读时间需要 11 分钟。

using System;

using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using YTLib.Basic;
using YTLib.YTDBC;
using System.IO;
using System.Threading;
namespace siteadmin.admin
{
    public partial class downfile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                 string strSQL = "";
                YTNDBObject dbo = new YTNDBObject();
                dbo.DataName = "Main";
            Page.EnableViewState = false;
            if(!IsPostBack)
            {
                string sid=Request["id"];
                if(!YTLib.publicOP.IsNumString(sid)||sid==null)
                    sid="0";
                strSQL = "select * from FileSource where ID=@ID";
                dbo.PrepareCommand(strSQL);
                dbo.SetCmdIntValue("@ID",int.Parse(sid));
                DataTable dt=dbo.QueryData().Tables[0];
                string sourceName = (string)dt.Rows[0]["FilePath"];
                sourceName.Trim();//消除空格
                string filesnames = sourceName.Substring(7, sourceName.Length - 8);
                int index= sourceName.LastIndexOf(".");
                string extend = sourceName.Substring(index+1);//扩展名
                string fullPath = "~/uploaded/" + sourceName;
                fullPath = Server.MapPath(fullPath);
                //读出该资源的下载次数
                int downloadtimes = 0;
                downloadtimes = int.Parse(dt.Rows[0]["downloadCounts"].ToString());
 
                         Page.Response.Clear();
                         bool success = ResponseFile(Page.Request, Page.Response, filesnames, fullPath, 1024000);
                if (!success) Response.Write("<script language=\"javascript\">alert(\"Download file error\");window.location.href=\"../Download.aspx\"</script>");
                else
                {
                    //记录下载次数
                    downloadtimes++;
                   string  sqlStr = "update FileSource set downloadCounts=" + downloadtimes + " where ID=@IID";
                   dbo.PrepareCommand(sqlStr);
                    dbo.SetCmdIntValue("@IID",int.Parse(sid));
                    dbo.ExecuteNoQuery();
                }
               Response.Write("<script language=\"javascript\">window.location.href=\"../Download.aspx\"</script>");
            }
        }
    public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
        try
        {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;//不缓冲
                long fileLength = myFile.Length;
                long startBytes = 0;
                double pack = 10240;
                //10K bytes
                int sleep = 200;
                //每秒5次 即5*10K bytes每秒 int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    //Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength-1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;
                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }
        }
    }

转载于:https://www.cnblogs.com/forbetterzhu/archive/2012/05/20/2510979.html

你可能感兴趣的文章
洛谷P1108 低价购买[DP | LIS方案数]
查看>>
通达信里的统计函数及区块背景函数
查看>>
redis主从配置<转>
查看>>
8 行 Node.js 代码实现代理服务器
查看>>
水印,图片验证码
查看>>
C#编程(七十六)----------使用指针实现基于栈的高性能数组
查看>>
PostgreSql 分页limit
查看>>
在MySQL中创建cm-hive使用的数据库及账号
查看>>
linux下限制ip访问
查看>>
linux添加环境变量
查看>>
Dumpsys Input Diagnostics
查看>>
ASP.NET MVC 入门8、ModelState与数据验证
查看>>
Understanding the Router
查看>>
组件居中显示 安卓
查看>>
delete
查看>>
sql server生成不重复的时间字符串
查看>>
DataBase 之 数据库设计六大范式
查看>>
比特币钱包安全
查看>>
Lucene就是这么简单
查看>>
2015年第6届蓝桥杯Java B组省赛试题解析
查看>>