如何显示字节流响应

问题描述:

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

我试图

Response.Write HttpReq.responseBody 

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

响应:

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

这是因为'回复于()'在当前'CodePage'写入文本回到浏览器,如果你想用'Response.BinaryWrite()'发回二进制数据。 – Lankymart

在传统的ASP,Response.Write()用于使用Response对象上定义的CodePageCharset属性文本数据发送回浏览器(默认情况下这是从继承当前会话并通过扩展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)你应该检查httpReq.Status让你单独处理任何错误返回二进制使用REST API时,即使设置了不同的content-type如果有错误。

您可以重构上述示例;

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

+0

在使用Response.BinaryWrite()在浏览器中编写一些奇怪的字符时,是否有办法将此二进制流转换为PDF文件并将其写入浏览器? 谢谢。 –

+0

@PrateekMishra *“奇怪的字符”*是出于某种原因二进制文本的表示形式,二进制不被视为有效的PDF。这里有几件事情要做,确保在Response之前调用Response.Clear()。BinaryWrite()'以避免恶意字符在二进制文件之前传递给浏览器,并确保'Response.ContentType'属性设置为适当的PDF MIME类型。 – Lankymart

+0

@PrateekMishra你是怎么过的?已经注意到这个问题在没有被接受的答案的情况下仍然是开放的,请考虑投票/接受答案,所以这个问题不会得到回答。 – Lankymart

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

在完整的示例中,我将在返回二进制文件之前检查'If httpReq.Status = 200 Then',以便可以独立处理任何错误,甚至可以切换内容类型。 – Lankymart

+0

谢谢,对于响应状态的好建议。对于内容类型,如果REST API调用应该返回二进制文件,我不认为这是必需的。 – krlzlx

+0

从技术上讲,'Content-Type'从来不需要,因为浏览器可以推断它,并不意味着你不应该明确地设置它。 – Lankymart