关于网页下载文件,使用数据流方式下载

关于文件下载,很多都是用href='文件地址',这样做是很不安全的,所以需要使用到文件流,以下代码用于下载一张图片。

     Response.BufferOutput = false;
        Response.Clear();
        Response.ContentType = "application/x-msdownload";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + "优惠券.jpg");
        Response.ContentType = "application/octstream";
        Response.CacheControl = "Private";
        System.IO.Stream stm = new System.IO.FileStream(Server.MapPath("~/uploadfiles/youhui/"+path), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
        Response.AppendHeader("Content-length", stm.Length.ToString());
        System.IO.BinaryReader br = new System.IO.BinaryReader(stm);
        byte[] bytes;
        for (Int64 x = 0; x < (br.BaseStream.Length / 4096 + 1); x++)
        {
            bytes = br.ReadBytes(4096);
            Response.BinaryWrite(bytes);
            System.Threading.Thread.Sleep(5);
        }

 

posted @ 2014-12-03 21:09  天VS涯2012  阅读(208)  评论(0)    收藏  举报