Writing a Base64 String to the File System or Browser

Quite often, vendors pass images or PDFs to customers using the binary contents of the file. To make it more secure, they convert the binary contents to a Base64 string. A full explanation about Base64 encoding can be found at Wikipedia here. Anyway, when you receive the string, you cannot simply write it to a file or to the browser. First, you must convert the data into a Byte array. The sample code below demonstrates this:

Dim str As String = "Insert Your Base64 String Here"
Dim Base64Byte() As Byte = Convert.FromBase64String(str)

Then, you can decide which output method you'd prefer. If you'd like to write the content to the file system, you can write it as:

Dim obj As FileStream = File.Create("C:\test.pdf")
obj.Write(Base64Byte, 0, Base64Byte.Length)
obj.Close()

If you'd prefer to write the content to the browser, you'd most likely add this to your page:

Response.ContentType = "application/pdf"
Response.BinaryWrite(Base64Byte)
Response.End()

I'd highly recommend setting the content-disposition header attribute if you write the file to the browser. I've explained more about using this header at http://weblogs.asp.net/jgaylord/archive/2004/12/08/278309.aspx.

Published Wednesday, October 10, 2007 4:18 PM by Jason N. Gaylord

Comments

# re: Writing a Base64 String to the File System or Browser

Sunday, January 13, 2008 8:25 AM by rupesh

any one can give me coding & important information for constructing web browser.

# re: Writing a Base64 String to the File System or Browser

Tuesday, September 16, 2008 6:56 AM by b64

VGhpcyBpcyB0aGUgcHJlYW1ibGUgYXJlYSBvZiBhIG11bHRpcGFydCBtZXNzYWdlLg0KTWFpbCByZWFkZXJzIHRoYXQgdW5kZXJzdGFuZCBtdWx0aXBhcnQgZm9ybWF0DQpzaG91bGQgaWdub3JlIHRoaXMgcHJlYW1ibGUuDQpJZiB5b3UgYXJlIHJlYWRpbmcgdGhpcyB0ZXh0LCB5b3UgbWlnaHQgd2FudCB0bw0KY29uc2lkZXIgY2hhbmdpbmcgdG8gYSBtYWlsIHJlYWRlciB0aGF0IHVuZGVyc3RhbmRzDQpob3cgdG8gcHJvcGVybHkgZGlzcGxheSBtdWx0aXBhcnQgbWVzc2FnZXMu

# re: Writing a Base64 String to the File System or Browser

Wednesday, January 21, 2009 1:30 PM by myjwels

hi,

Is is possible to convert base64 string to it's original format without specifying the fileformat.

thanks,

Hema

Leave a Comment

(required) 
(required) 
(optional)
(required)