在ASP.Net(與C#)我試圖創建一個純文本的.DAT文件,並將其發送到瀏覽器並強制下載。我嘗試了幾件事,但我無法得到它的工作。在我的aspx文件有一個ImageButton
強制下載ASP.Net
<asp:ImageButton ID="btnSave" runat="server" CausesValidation="False" ImageUrl="~/Images/Stages/Database/Save.png" OnClick="btnSave_OnClick" Width="26px" />
在onclick法我試圖創建文件,並將其發送給瀏覽器。
protected void btnSave_OnClick(object sender, EventArgs e)
{
string file = "test.dat";
string fileName = "~\\Stages\\Broekx\\Databanken\\" + file;
FileStream fs = new FileStream(MapPath(fileName), FileMode.Open);
long cntBytes = new FileInfo(MapPath(fileName)).Length;
byte[] byteArray = new byte[Convert.ToInt32(cntBytes)];
fs.Read(byteArray, 0, Convert.ToInt32(cntBytes));
fs.Close();
ImageButton btnSave = (ImageButton)FormViewStagesDummy.FindControl("btnSave");
btnSave.Visible = false;
File.Delete(Server.MapPath(fileName));
if (byteArray != null)
{
this.Response.Clear();
this.Response.ContentType = "text/plain";
this.Response.AddHeader("content-disposition", "attachment;filename=" + file);
this.Response.BinaryWrite(byteArray);
this.Response.End();
this.Response.Flush();
this.Response.Close();
}
}
文件test.dat存在於正確的文件夾中,並且在讀入字節後必須刪除。我已經試過這個而不刪除文件,也不會工作。
點擊btnSave後,按鈕必須隱藏,所以我將參數Visible設置爲false。
我也試過它與內容類型的「應用程序/八位字節流」或與PDF文件和內容類型「應用程序/ pdf」,但沒有任何作品。頁面正常加載並且沒有文件正在被下載。
我懷疑響應的某些部分會在頭部之前發送。我也不明白你期望單個響應如何下載文件,並同時使按鈕不可見。 – CodesInChaos 2012-02-14 13:47:26
我以爲類似的東西,但我怎麼做這項工作? – Yoni 2012-02-14 13:49:49
作爲旁註:查看'File.ReadAllBytes',它可以替換您用來讀取文件的5行。你應該只用非常小的文件來做到這一點,或許高達10kB。 – CodesInChaos 2012-02-14 13:50:40