I lately realized that people who are using my technique to convert a file to a base64 string in javascript are searching out for a solution to convert base64 to a file. This article mainly concentrates on converting the base64 back to the respective file with their respective formats.
There are many ways to achieve it.
Let’s say you know the base64 string is a pdf object , then just use a line
1 | window.open("data:application/pdf;base64," + Base64.encode(base64)); |
Different browsers will behave differently on this statement, some will open the pdf in a new window where as some will pop-up a window which expects the user to open the file with a specific application based on operating system or save the file.
If your requirement is to convert the base64 string to TIFF or DOC etc then prefer converting the base64 string to a blob and downloading it since many browsers would not support opening of files with those extensions.
Assuming you get the MIME type with the base64 string in a response object,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | function checkForMIMEType(response) { var blob; if (response.mimetype == 'pdf') { blob = converBase64toBlob(response.content, 'application/pdf'); } else if (response.mimetype == 'doc') { blob = converBase64toBlob(response.content, 'application/msword'); /*Find the content types for different format of file at http://www.freeformatter.com/mime-types-list.html*/ } var blobURL = URL.createObjectURL(blob); window.open(blobURL); } function converBase64toBlob(content, contentType) { contentType = contentType || ''; var sliceSize = 512; var byteCharacters = window.atob(content); //method which converts base64 to binary var byteArrays = [ ]; for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) { var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } var blob = new Blob(byteArrays, { type: contentType }); //statement which creates the blob return blob; } |
I hope the article is helpful.
Happy Coding……..:)