2013年4月19日 星期五

ASP.NET的下載範例

 

適用在

window.open('download.aspx', '', 'toolbar=no,scrollbars=no,menubar=no,status=no,width=800,height=600');

不能用在下面這個敘述(不會產生預期的效果)

window.showModalDialog('download.aspx', '', 'dialogWidth: 800px;status:no;scroll:auto;toolbar:no;location:no');

使用下面的Tag Statement

<a id="DownLoadExcel" runat="server" Text="下載" onserverclick="DownloadExcel_Click"  >
    <asp:Literal runat="server" Text="下載" />
</a>

引用的函數如下:

protected void DownloadExcel_Click(object sender, EventArgs e)
{
    String NavigateUrl = "~/RelPath/sample." + this.CurrentLanguage + ".xls";
    FileInfo fileInfo = new FileInfo(Server.MapPath(NavigateUrl));
    Response.Clear();
    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("Content-Length", fileInfo.Length.ToString());
    //Content-Disposition Start
    //Content-Disposition 會影響下載視窗的顯示方式,沒有Content-Disposition也可下載)
    String FileName = fileInfo.Name;
    if (Request.Browser.Browser == "IE")
    {
        FileName = Server.UrlPathEncode(FileName);
    }
    string strContentDisposition = String.Format("{0}; filename=\"{1}\"", "attachment", FileName);
    Response.AddHeader("Content-Disposition", strContentDisposition);
    //Content-Disposition End
	
    Response.WriteFile(fileInfo.FullName);
    Response.Flush();
    Response.End();
    //ApplicationInstance.CompleteRequest();
}

沒有留言:

張貼留言