2017-02-17 66 views
2

我的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

回答

1

在傳統的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

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 
+0

在完整的示例中,我將在返回二進制文件之前檢查'If httpReq.Status = 200 Then',以便可以獨立處理任何錯誤,甚至可以切換內容類型。 – Lankymart

+0

謝謝,對於響應狀態的好建議。對於內容類型,如果REST API調用應該返回二進制文件,我不認爲這是必需的。 – krlzlx

+0

從技術上講,'Content-Type'從來不需要,因爲瀏覽器可以推斷它,並不意味着你不應該明確地設置它。 – Lankymart