如何显示字节流响应

时间:2017-02-17 06:40:05

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

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

我试过

Response.Write HttpReq.responseBody

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

REST API的响应:

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

2 个答案:

答案 0 :(得分:2)

您必须将响应的内容类型定义为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

答案 1 :(得分:1)

在Classic ASP中,Response.Write()用于使用CodePage对象上定义的CharsetResponse属性将文本数据发送回浏览器(按默认情况下,这是从当前会话继承而来的,是IIS服务器配置的扩展名。

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

以下是一个简单的示例(基于您已经拥有httpReq.ResponseBody二进制文件的代码段;

<%
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
%>