Asp.net 响应。重定向不起作用
我正在编写一个代码,在点击一个按钮后,一个页面将被重定向到另一个页面,打开第二页后,一个pdf文件将被下载,就像这个网站一样。但不是打开第二页并下载pdf文件,而是只下载pdf文件,但第二页没有打开。第一页代码是Asp.net 响应。重定向不起作用,asp.net,Asp.net,我正在编写一个代码,在点击一个按钮后,一个页面将被重定向到另一个页面,打开第二页后,一个pdf文件将被下载,就像这个网站一样。但不是打开第二页并下载pdf文件,而是只下载pdf文件,但第二页没有打开。第一页代码是 protected void Button1_Click(object sender, EventArgs e) { Response.Redirect("2nd.aspx"); } 第二页的代码写在下面 protected void Page_Load(object send
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("2nd.aspx");
}
第二页的代码写在下面
protected void Page_Load(object sender, EventArgs e)
{
string filepath = "guar-gum/Guar-gum-export-report.pdf";
// The file name used to save the file to the client's system..
string filename = Path.GetFileName(filepath);
System.IO.Stream stream = null;
try
{
// Open the file into a stream.
stream = new FileStream(Server.MapPath("Guar-gum-export-report.pdf"), System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
// Total bytes to read:
long bytesToRead = stream.Length;
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
// Read the bytes from the stream in small portions.
while (bytesToRead > 0)
{
// Make sure the client is still connected.
if (Response.IsClientConnected)
{
// Read the data into the buffer and write into the
// output stream.
byte[] buffer = new Byte[10000];
int length = stream.Read(buffer, 0, 10000);
Response.OutputStream.Write(buffer, 0, length);
Response.Flush();
// We have already read some bytes.. need to read
// only the remaining.
bytesToRead = bytesToRead - length;
}
else
{
// Get out of the loop, if user is not connected anymore..
bytesToRead = -1;
}
}
Response.Flush();
}
catch (Exception ex)
{
Response.Write(ex.Message);
// An error occurred..
}
finally
{
if (stream != null)
{
stream.Close();
//
}
}
}
你希望在第二页看到什么?你只有一个pdf文件。你希望看到一页空白吗 你的重定向工作正常。当您单击该按钮时,PDF文件将发送回浏览器,并将其视为应下载的文件。不会向浏览器发送任何页面,因此没有可查看的页面。以下是解决方案: 不要将您在page2.aspx中所做的工作编码为文件下载,而是在page2.aspx中放置一个
iframe
,并将src
设置为文件Url
我猜你的情况是guar-gum/guar-gum export report.pdf
。可能您应该将其更改为从站点的根目录开始,并将前缀/
更改为文件url
把这个放到page2.aspx
这是一种非常简单的方法,没有重定向或JavaScript,您的Page2.aspx也将打开
更新
根据下面的评论,这个答案
我认为没有更好的解决方案,但这里有另一个令人费解的解决方案(psst!希望你和其他类似的人…)将page2.aspx代码移动到第三页page3.aspx,并将iframe.src
设置为page3.aspx
参考文献
您已经编写了在page2的响应流中发送pdf的代码,这是导致此行为的原因。但是如何处理ovrcm ds问题确定。请帮我解决frm ds问题您的第一个选项不起作用。你能帮助我如何实现下载选项吗handler@SoumitaP我又读了一遍这个问题。问题类似于我的重播,你不能同时拥有这两个,下载并显示页面。请检查页面并单击“立即下载”按钮。。我希望在我的页面中也有同样的内容。发生了什么?错误消息或行为改变或其他?第二页正在打开,但pdf未下载。好的,我认为没有更好的解决方案,但这里有另一个令人费解的解决方案(psst希望您和其他类似的人)。。将仅用于文件下载的page2.aspx代码移到第三页page3.aspx,并将
iframe.src
设置为page3.aspx此iframe概念不起作用。。。有没有其他方法可以解决这个问题?好的,这是我创建的示例演示站点。在chrome或其他浏览器中打开,如果未出现dwld,则按ctrl+s保存文件,并将其重命名为.zip from.gif以查看源文件。