• 文件下载


    在你的Page_Load中添加这样的代码:

     Page.Response.Clear();
     
    bool success = ResponseFile(Page.Request, Page.Response, "目的文件名称"@"源文件路径"1024000);
     
    if (!success)
         Response.Write(
    "下载文件出错!");
    Page.Response.End();

    文件下载函数代码为:
    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;
        }


    这样就实现了文件下载时,不管是什么格式的文件,都能够弹出打开/保存窗口.

    防止盗链

    protected void Page_Load(object sender, EventArgs e)
    {
    /*--------------------------------------------------------------*\
    * 大文件下载,防盗链 *
    * *
    * tda7264@163.com *
    * *
    * 飘遥的BLOG
    http://xianfen.net *
    \* -------------------------------------------------------------
    */

    if (Request.QueryString["FileName"] == null)
    {
    InvalidRedirect();
    }

    string fileName = Request.QueryString["FileName"];

    if (fileName == string.Empty)
    {
    InvalidRedirect();
    }

    //判断配置文件是否直接下载
    string downDirect = ConfigurationManager.AppSettings["Down"].ToLower();

    if (downDirect == "true")
    {
    UpdateHits(fileName);
    //更新下载次数
    Response.Redirect("Upload/" + fileName);
    return;
    }

    string path = Server.MapPath(Request.ApplicationPath + "/Upload/" + fileName);
    string referrer = string.Empty;

    if (Request.UrlReferrer != null)
    {
    referrer
    = Request.UrlReferrer.ToString().ToLower();
    }

    string d = ConfigurationManager.AppSettings["Valid"].ToLower();
    string[] domainName =
    ConfigurationManager.AppSettings[
    "Refers"].ToLower().Split(new char[] { ',' });

    // 如果设置为防止盗链,判断访问来源是否合法
    if (d == "false")
    {
    foreach (string s in domainName)
    {
    if (referrer.IndexOf(s.ToLower()) > 0)
    {
    UpdateHits(fileName);
    //更新下载次数
    ResponseFile(path);
    return;
    }
    }

    InvalidRedirect();
    }
    else
    {
    ResponseFile(path);
    }
    }

    protected void UpdateHits(string fileName)
    {
    //更新文件下载次数的代码
    }

    protected void InvalidRedirect()
    {
    string defaultPage = ConfigurationManager.AppSettings["DefaultRedirect"];

    Response.Redirect(defaultPage,
    true);
    }


    配置文件
    配置文件中配置下载方式、盗链功能是否开启及盗链默认转向的页面地址:

    <appSettings>
    <add key="Down" value="false"/>
    <!--是否直接下载-->
    <add key="Valid" value="false"/>
    <!--是否允许盗链-->
    <add key="Refers" value="localhost,google.cn"/>
    <!--多个允许的访问来源用半角的","分割-->
    <add key="DefaultRedirect" value="Error.htm"/>
    <!--默认转向的页面-->
    </appSettings>

    /************************************************/

    本博客内容如果是原著都会在标题后加上(原著)字样,未加者多数为转载.

    /************************************************/

  • 相关阅读:
    传统项目管理工具-scrum敏捷开发看板工具
    免费脑图软件
    项目管理软件收藏
    Scrum看板项目研发管理软件Leangoo- 阶段式游戏产品研发
    【Android开发日记】之入门篇(十二)——Android组件间的数据传输
    Android捕获崩溃异常
    【Android开发日记】之入门篇(十一)——Android的Intent机制
    Git的简单使用
    【Android开发日记】之入门篇(十)——Android应用配置文件解析
    【Android开发日记】之入门篇(九)——Android四大组件之ContentProvider
  • 原文地址:https://www.cnblogs.com/ghfsusan/p/1749593.html
Copyright © 2020-2023  润新知