【发布时间】:2018-05-02 22:47:23
【问题描述】:
我有一个网页链接到一些 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 在新窗口中打开吗?
【问题讨论】:
-
为什么不响应.WriteFile?
-
为什么不能使用 target=_blank。你能解释一下原因吗?我认为,使用 HTTP 处理程序可以解决您的目的。
-
你能给我一个例子 Response.WriteFile 如何在新窗口中打开链接?谢谢
-
suryakiran - 我正在使用httphandler拦截请求,并在用户登录后将用户重定向到登录页面,执行上面下载文件的代码
-
你能用这样的把戏吗?
Response.Write("<script>window.open('+FilePath+','_blank');</script>");通过这种方式,您将根据需要将动态 JS 添加到您在 _blank 目标中打开的页面中,而无需触及基本代码。