使用流防盜鏈下載大文件javascript
直接上 Asp.net 後置代碼好了java
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>"); } } }