因工作需要,想在網站上做到讓User在客戶端自由點選pdf檔,選完後一次打包下載。本想利用jQuery ajax將客戶選定的資料送回後端處理後,再Response.BinaryWrite出來。怎知jQuery報錯。原來要進行檔案下載,是不能以ajax方式,而必須讓網頁postback回後端,經後端處理後Response.BinaryWrite出來。但畫面User選定的值會被洗掉,且不想讓畫面"閃"一下。參考了網路上前輩們的作法,決定利用iframe這個html tag來實作。
思路:當user點選button後,會call 一支javascript function,該function會在html body中append一個iframe,並指定iframe的src(../download.aspx)。此時iframe會根據指定的src載入download.aspx。而在download.aspx的code-behind Page_Load中,撰寫將多個pdf檔壓縮成zip的程式,並傳回客戶端。
經過孤狗大神的指示,找到了DotNetZip這個好用的壓縮/解壓縮元件。
Default.aspx:
(1)HTML部分:
<body>
<form id="form1" runat="server">
<div>
<a href="#" onclick="dowork()">下載</a>
</div>
</form>
</body>
(2)Javascript部分:
<script src="Scripts/jquery-2.0.0.min.js"></script>
<script type="text/javascript">
function dowork() {
var $iframe = $('<iframe></iframe>');
//指定iframe的src並將其設為隱藏
$iframe.attr('src', 'download.aspx').css('display','none');
$('body').append($iframe);
}
</script>
download.aspx:
protected void Page_Load(object sender, EventArgs e)
{
//string id = Request["id"];
//string name = Request["name"];
download_pdf();
}
private void download_pdf()
{
var memoryStream = new System.IO.MemoryStream();
//若遇到中文檔名,但未加System.Text.Encoding.Default,則檔案會無法AddFile。
using (var zip = new Ionic.Zip.ZipFile(System.Text.Encoding.Default))
{
string path = Server.MapPath(@"\ebook\");
zip.AddFile(path + "ado打內.pdf","e-book");
zip.AddFile(path + "asp_net.pdf", "e-book");
zip.Save(memoryStream);
}
Response.ContentType = "application/zip";
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Report.zip"));
HttpContext.Current.Response.BinaryWrite(memoryStream.ToArray());
}
DotNetZip download : http://dotnetzip.codeplex.com/
DotNetZip document:http://dotnetzip.herobo.com/DNZHelp/Index.html