使用流防盗链下载大文件
直接上 Asp.net 后置代码好了
using System; using System.Data; using System.Configuration; using System.Collections; 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.IO; public partial class FileDownload_Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } //以流方式下载文件,适合大文件 protected void btn_down_Click(object sender, EventArgs e) { try { //设置文件名 Response.AddHeader("Content-Disposition", "attachment; filename=test.jpg"); Response.ContentType = "application/octet-stream"; //设置下载文件的服务器路径 String filePath = "~/FileDownload/test.jpg"; //输出到流 FileStream stream = new FileStream(Server.MapPath(filePath), FileMode.Open, FileAccess.Read, FileShare.Read); BinaryReader reader = new BinaryReader (stream); Response.Clear(); while (true) { byte [] bt = reader.ReadBytes(1000); Response.OutputStream.Write(bt,0,1000); if(bt.Length<1000) break; } reader.Close(); stream.Dispose(); Response.End(); } catch(Exception ex) { this.ClientScript.RegisterStartupScript(this.GetType(),"new","<mce:script type="text/javascript"><!-- alert('下载文件异常 : "+ex.Message+"'); // --></mce:script>"); } } }