Prateek Mishra
Prateek Mishra

Reputation: 9

How to show a byte stream response

My REST API returns a PDF document in bytes and I need to call that API and show the PDF document on the ASP page for previewing to the user.

I tried

Response.Write HttpReq.responseBody

but it's writing some unreadable text on the page. The httpReq is my object through which I am calling the REST API.

Response of REST API:

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

Upvotes: 0

Views: 2113

Answers (2)

user692942
user692942

Reputation: 16681

In Classic ASP, Response.Write() is used to send textual data back to the browser using the CodePage and Charset properties defined on the Response object (by default this is inherited from the current Session and by extension the IIS Server Configuration).

To send binary data back to the browser use Response.BinaryWrite().

Here is a quick example (snippet based off you already having the binary from 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)
%>

Ideally, when using a REST API via an XHR (or any URL for that matter) you should be checking the httpReq.Status to allow you to handle any errors separately to returning the binary, even set a different content-type if there is an error.

You could restructure the above example;

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

Upvotes: 1

krlzlx
krlzlx

Reputation: 5822

You'll have to define the content type of the response as PDF:

Response.ContentType = "application/pdf"

Then write the binary data to the response:

Response.BinaryWrite(httpReq.ResponseBody)

Full example:

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

Upvotes: 1

Related Questions