如何在新的选项卡或窗口中打开PDF文件而不是下载(使用asp.net)?

smi*_*ilu 15 c# pdf asp.net stream

这是下载文件的代码.

System.IO.FileStream fs = new System.IO.FileStream(Path+"\\"+fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] ar = new byte[(int)fs.Length];
fs.Read(ar, 0, (int)fs.Length);
fs.Close();

Response.AddHeader("content-disposition", "attachment;filename=" + AccNo+".pdf");
Response.ContentType = "application/octectstream";
Response.BinaryWrite(ar);
Response.End();
Run Code Online (Sandbox Code Playgroud)

执行此代码时,它将要求用户打开或保存文件.而不是这个我需要打开一个新的选项卡或窗口并显示该文件.我怎样才能做到这一点?

注意:

文件不必位于网站文件夹中.它可能位于其他文件夹中.

jan*_*nzi 18

您应该查看HttpResponse.TransmitFile,而不是将流加载到字节数组并将其写入响应流.

Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);
Run Code Online (Sandbox Code Playgroud)

如果您希望在新窗口中打开PDF,则必须在新窗口中打开下载页面,例如:

<a href="viewpdf.aspx" target="_blank">View PDF</a>
Run Code Online (Sandbox Code Playgroud)

  • 不幸的是,只有在某个地方存储了实际文件时,这才有效.如果你有一个例如生成的字节数组,则没有'path' - 呈现Response.TransmitFile无用.至少这就是我遇到的情况. (4认同)
  • 您无法从服务器端打开新窗口.您必须在新窗口中打开下载页面,并在该窗口中使用TransmitFile将文件返回给用户. (3认同)

Nin*_*ina 10

Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
Response.BinaryWrite(fileContent);
Run Code Online (Sandbox Code Playgroud)

<asp:LinkButton OnClientClick="openInNewTab();" OnClick="CodeBehindMethod".../>
Run Code Online (Sandbox Code Playgroud)

在javaScript中:

<script type="text/javascript">
    function openInNewTab() {
        window.document.forms[0].target = '_blank'; 
        setTimeout(function () { window.document.forms[0].target = ''; }, 0);
    }
</script>
Run Code Online (Sandbox Code Playgroud)

注意重置目标,否则所有其他调用Response.Redirect将在新选项卡中打开,这可能不是您想要的.


Kar*_*hik 2

这可能有帮助

Response.Write("<script>");
Response.Write("window.open('../Inventory/pages/printableads.pdf', '_newtab');");
Response.Write("</script>");
Run Code Online (Sandbox Code Playgroud)