【问题标题】:How to show a byte stream response如何显示字节流响应
【发布时间】:2017-02-17 06:40:04
【问题描述】:

我的 REST API 以字节为单位返回 PDF 文档,我需要调用该 API 并在 ASP 页面上显示 PDF 文档以供用户预览。

我试过了

Response.Write HttpReq.responseBody

但它在页面上写了一些不可读的文本。 httpReq 是我调用 REST API 的对象。

REST API 的响应:

Request.CreateResponse(HttpStatusCode.OK, pdfStream, MediaTypeHeaderValue.Parse("application/pdf"))

【问题讨论】:

  • 那是因为Response.Write()将当前CodePage中的文本写回浏览器,如果要发回二进制数据使用Response.BinaryWrite()

标签: vb.net asp.net-web-api vbscript asp-classic


【解决方案1】:

您必须将响应的内容类型定义为 PDF:

Response.ContentType = "application/pdf"

然后将二进制数据写入响应:

Response.BinaryWrite(httpReq.ResponseBody)

完整示例:

url = "http://yourURL"

Set httpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open "GET", url, False
httpReq.Send

If httpReq.Status = "200" Then
    Response.ContentType = "application/pdf"
    Response.BinaryWrite(httpReq.ResponseBody)
Else
    ' Display an error message
    Response.Write("Error")
End If

【讨论】:

  • 在完整示例中,我会在返回二进制文件之前检查If httpReq.Status = 200 Then,以便可以独立处理任何错误,甚至可以切换内容类型。
  • 谢谢,关于响应状态的好建议。对于内容类型,如果 REST API 调用应该返回二进制文件,我认为不需要这样做。
  • 从技术上讲,永远不需要Content-Type,因为浏览器可以推断它,但这并不意味着您不应该明确设置它。
  • 如果您在服务器标头中有​​:X-Content-Type-Options=nosniff,浏览器将不会进行 MIME 类型的嗅探。
  • 是的,但不是 IIS 上的默认设置。但是,更有理由明确设置 Content-Type 标头。
【解决方案2】:

在经典 ASP 中,Response.Write() 用于使用在 Response 对象上定义的 CodePageCharset 属性将文本数据发送回浏览器(默认情况下,这是从当前 Session 继承的并通过扩展 IIS 服务器配置)

要将二进制数据发送回浏览器,请使用Response.BinaryWrite()

这是一个简单的示例(基于您已经拥有来自httpReq.ResponseBody 的二进制文件的sn-p);

<%
Response.ContentType = "application/pdf"
'Make sure nothing in the Response buffer.
Call Response.Clear()
'Force the browser to display instead of bringing up the download dialog.
Call Response.AddHeader("Content-Disposition", "inline;filename=somepdf.pdf")
'Write binary from the xhr responses body.
Call Response.BinaryWrite(httpReq.ResponseBody)
%>

理想情况下,当通过 XHR (或任何 URL)使用 REST API 时,您应该检查 httpReq.Status 以允许您单独处理任何错误以返回二进制文件,即使如果出现错误,请设置不同的内容类型。

你可以重构上面的例子;

<%
'Make sure nothing in the Response buffer.
Call Response.Clear()
'Check we have a valid status returned from the XHR.
If httpReq.Status = 200 Then
  Response.ContentType = "application/pdf"
  'Force the browser to display instead of bringing up the download dialog.
  Call Response.AddHeader("Content-Disposition", "inline;filename=somepdf.pdf")
  'Write binary from the xhr responses body.
  Call Response.BinaryWrite(httpReq.ResponseBody)
Else
  'Set Content-Type to HTML and return a relevant error message.
  Response.ContentType = "text/html"
  '...
End If
%>

【讨论】:

  • 使用 Response.BinaryWrite() 在浏览器中写入一些奇怪的字符时,是否有办法将此二进制流转换为 pdf 文件并在浏览器上写入?谢谢。
  • @PrateekMishra “奇怪的字符” 出于某种原因是二进制文件的文本表示,二进制文件不被视为有效的 PDF。这里有几件事要尝试,确保在Response.BinaryWrite() 之前调用Response.Clear() 以避免在二进制文件之前将流氓字符传递给浏览器,并确保将Response.ContentType 属性设置为适当的PDF mime 类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多