[英]Facing an issue downloading a file to client using stream in asp.net
我試圖使用Http Response在asp.net的客戶端上創建(流)並下載html文件。
在這里瀏覽了許多相關文章,但沒有任何幫助。 花了將近兩天的時間后,我偶然發現了一個解決方案。
但是,現在想了解原因,為什么它較早失敗。
這是故事:
請考慮以下ASP.net代碼隱藏處理程序。
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploadControl.HasFile)
{
try
{
if (FileUploadControl.PostedFile.ContentType == MIMEAssistant.GetMIMEType(".xls"))
{
string filename = "log.htm";
string logContent = "This is a test log..";
// Some upload processing..
// Send log file for download
Response.Clear();
Response.ContentType = MIMEAssistant.GetMIMEType(filename);
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
using (StreamWriter writer = new StreamWriter(Response.OutputStream, Encoding.ASCII))
{
writer.Write(logContent);
}
//Response.OutputStream.Write(buf1, 0, buf1.Length);
HttpContext.Current.ApplicationInstance.CompleteRequest();
Response.End();
}
else
StatusLabel.Text = "Upload status: Only .xls files are accepted!";
}
catch (Exception ex)
{
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
}
}
}
IE並沒有真正幫助使IE下載文件並避免卡死。 最后,從函數的最內層到最外層提取“ //發送要下載的日志文件”下的代碼即可解決該問題。
編輯:即使刪除了下面解釋的罪魁禍首,仍然再次面臨問題。
請幫我理解為什么?
注意:在上面的代碼中,語句Response.End()引發了一個異常,內容為:
[System.Threading.ThreadAbortException] = {由於代碼已優化或本機框架位於調用堆棧的頂部,因此無法評估表達式。}
更多信息:在進一步研究並創建了示例應用程序之后,我發現將下載代碼放入以下代碼會導致此問題:
if (FileUploadControl.HasFile)
{
try
{
this.HtmlLogDownload();
}
catch (Exception ex)
{
throw ex;
}
}
如果刪除,效果很好:
如果(FileUploadControl.HasFile)
這也是網絡表單代碼:
<form id="form1" runat="server">
<asp:FileUpload ID="FileUploadControl" runat="server" />
<asp:Button runat="server" ID="UploadButton" Text="Upload" OnClick="UploadButton_Click" />
<div>
</div>
</form>
編輯:以上工作在Chrome和Mozilla中。 IE 11中失敗
我注意到IE11像這樣檢查時,返回的上傳的.png圖像為:“ application / png”:LabelStatus.Text =“ Ongeldig afbeeldingstype:”&FileUploadKleinLogo.PostedFile.ContentType
以前是“ image / png”
我的猜測是那是導致IE11而不是FF或Chrome出現問題的原因
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.