【问题标题】:Using memorystream to make a pdf download using VB.NET and Webforms使用 memorystream 使用 VB.NET 和 Webforms 进行 pdf 下载
【发布时间】:2017-09-26 23:34:48
【问题描述】:

我有一个我编写的方法,它调用 ReportServer 并返回报告的 pdf 的字节数组。这行得通。我知道是因为我使用相同的方法将 pdf 写入文件并将其保存在本地。在这里,我想将文件写入内存流并作为下载提供。

    Try
        Dim ms As MemoryStream = New MemoryStream(report, 0, report.Length)
        ms.Position = 0

        Response.Clear()
        Response.Expires = 0
        Response.Buffer = True
        Response.AddHeader("Content-disposition", "attachment;filename=UserReport.pdf")
        Response.ContentType = "application/pdf"
        'ms.WriteTo(Response.OutputStream)
        Response.BinaryWrite(ms.ToArray())
        Response.End()
        HttpContext.Current.ApplicationInstance.CompleteRequest()
        'Response.Flush()

    Catch ex As Exception
        lblERRORMSG.Visible = True
        lblERRORMSG.Text = "Darn!" & ex.Message
        Return
    End Try
End Sub`

这段代码可以编译、运行,我什至可以设置被命中的断点。但是当按钮被点击时,什么也没有发生。

【问题讨论】:

  • HttpContext.Current.ApplicationInstance.CompleteRequest() 永远不会受到打击。 Response.End() 按设计抛出 ThreadAbortException
  • 我已经看到 Response.End() 抛出异常,但消息是一个空字符串,所以我想保留该代码以捕获任何其他异常。
  • 您应该将 Response.End 移到 try/catch 之外。并抛弃 CompleteRequest。
  • 仍然没有给我下载。我还摆脱了 Catch 中的返回...我认为这会导致 Response.End() 被跳过。
  • 使用浏览器的调试工具检查网络流量。当您尝试下载时会发生什么?

标签: asp.net vb.net pdf


【解决方案1】:

有问题的代码没有任何问题。该代码与由telerik 制造的称为RadAjaxPanel 的UpdatePanel 一起使用。使用此控件的页面上的按钮的默认设置是它们不会回发。解决方案很简单。您需要在后面的代码中转到 Page_Load 事件并添加以下代码:

ScriptManager1.RegisterPostBackControl(btnNameGoesHere)

这将在单击按钮时触发回发!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多