[英]Response.Redirect is not working
我正在编写代码,单击一个按钮后,将打开第二页后将一页重定向到另一页,就像此网站http://www.findwhitepapers.com/content22881一样,将下载一个pdf文件。但不是打开第二页页并下载pdf文件,只有pdf文件已下载,但第二页未打开。第一页代码为
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中所做的用于文件下载的代码,而是将一个iframe
放在page2.aspx中,并将src
设置为文件Url。
我猜这是您的情况下guar-gum/Guar-gum-export-report.pdf
。 可能是您应该将其更改为从站点的根开头(以前缀/
开头)到文件url。
把它放在page2.aspx中
<iframe width="1" height="1" frameborder="0" src="[File location]"></iframe>
这是非常简单的方法,并且没有重定向或JavaScript,您的Page2.aspx也将打开。
根据此答案下方的评论
我认为没有更好的解决方案,但是这是另一种弯腰的解决方案(psst!希望您和其他人都喜欢..)将仅文件下载的page2.aspx代码移至第三页page3.aspx,并将iframe.src
设置为iframe.src
。 aspx
参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.