0

我有一个网页链接到一些 pdf 文件,例如http://www.someurl.com/somefolder/filename.pdf

当用户单击这些链接时,身份验证启动,用户登录并可以下载文件。我想要实现的是下载在新窗口中打开。

我对代码的访问/控制有限,无法将target=_blank属性添加到 href 或添加任何 javascript。认证后下载的代码如下:

string filename = Path.GetFileName(context.Request.PhysicalPath);

FileStream MyFileStream;
long FileSize;

string strMapPath = context.Server.MapPath(filename);
MyFileStream = new FileStream(strMapPath, FileMode.Open);
FileSize = MyFileStream.Length;

//Allocate size for our buffer array
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)FileSize);
MyFileStream.Close();

//Do buffer cleanup
context.Response.Buffer = true;
context.Response.Clear();

//Add the appropriate headers
context.Response.AddHeader("content-disposition",
"attachement filename=" + filename);

//Add the right contenttype
context.Response.ContentType = "application/pdf";

//Stream it out via a Binary Write
context.Response.BinaryWrite(Buffer);

我们可以强制context.Response在新窗口中打开吗?

4

2 回答 2

3

打开新窗口是客户端操作,Context.Response而是服务器端命令。要打开新窗口,您需要在客户端做一些事情。

如果您无法更改原始页面源以运行脚本或更改 HTML,那么您想要的就无法完成。您可以根据请求返回一个页面,该页面具有打开新窗口的脚本,但它不会相同。您要么必须完全重新创建原始页面,除非使用添加的脚本(如果可以这样做,我假设您可以更改原始页面),或者您将有一个不同的页面来打开弹出窗口。

唯一好的解决方案是更改原始页面以添加弹出脚本,target="_blank"或者使用添加 onclick 处理程序到链接的脚本。这两个你说你做不到。

于 2013-05-21T13:09:05.337 回答
0

我知道这已经过时了,但这就是我为实现 OP 所做的工作。

首先,您似乎走在了正确的轨道上,但我注意到您的附件拼写错误并且忘记提供“;” 直接在“附件”内容处置声明之后。

这是我使用的原始代码,它显示了与您描述的相同的行为!

将您的内容处置声明更改为此

Response.AddHeader("Content-Disposition", "attachment; filename=" + docName + ".pdf");

补充说明

  • 如果将 Content-Disposition 指定为“Inline”,它将在当前窗口中输出文件内容。

  • 您需要将该配置更改为“附件”,并确保您的扩展后缀明确设置为 .pdf。

于 2018-05-02T14:47:23.683 回答