Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response.Write Base64 string

Tags:

c#

http

asp.net

I receive a Base64 string which is actually the string representation of a PDF file. I want to write this string with Response.Write, but without converting it back to its binary representation.

I tried this:

var base64string = "...";
Response.Write(base64String);
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Transfer-Encoding", "base64");

The browser does not recognize the content as a base64 encoded PDF file. How can I fix this?

EDIT: this is the response

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: application/pdf; charset=utf-8
Vary: Accept-Encoding
Server: Microsoft-IIS/7.5
Content-Transfer-Encoding: base64
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 11 Apr 2012 11:00:04 GMT
Content-Length: 107304

JVBERi0xLjQKJeLjz9MKMSA... more content here
like image 358
Adrian Iftode Avatar asked Feb 20 '23 20:02

Adrian Iftode


2 Answers

Content-Transfer-Encoding is not a valid HTTP header; this is an old header from MIME. It's HTTP equivalent is Transfer-Encoding which supports the following values:

  • chunked
  • identity
  • gzip
  • compress
  • deflate

If you have a Base64 encoded PDF document, there isn't a "from base64" transform in HTTP which will decode this document for you, so you must decode it on your server, prior to putting it in the response body.

If you want a stream that converts from Base64, you can use a FromBase64Transform into a CryptoStream:

new CryptoStream(fileStream, new FromBase64Transform(), CryptoStreamMode.Read)
like image 81
Paul Turner Avatar answered Feb 23 '23 11:02

Paul Turner


When you promise a PDF with

 Response.ContentType = "application/pdf";

You should also deliver one by opening the Response Stream and write the binary version of the PDF there.

like image 27
Henk Holterman Avatar answered Feb 23 '23 11:02

Henk Holterman