If you are uploading binary documents like pdf’s, images, word files ect., and you want to see what you have uploaded, or you want to view documents uploaded by someone else in a web application, you can use the following code to open a tab in the web browser or download a document to your device.
The function expects a base64 value of the binary document to be passed, which is then converts to a blob before finding the correct MIME type and opening a new tab window to display the document.
Please note you can find more MIME type values at Common MIME types - HTTP | MDN
displayFile: function(base64, fileName) {
var self = this;
var byteCharacters = atob(base64);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var fileType = fileName.split(".")[1];
var typeValue = "";
switch(fileType) {
case "pdf":
typeValue = "application/pdf;base64";
break;
case "png":
typeValue = "image/png;base64";
break;
case "gif":
typeValue = "image/gif;base64";
break;
case "jpeg":
typeValue = "image/jpeg;base64";
break;
case "jpg":
typeValue = "image/jpg;base64";
break;
case "docx":
typeValue = "application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64";
break;
}
var file = new Blob([byteArray], { type: typeValue });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}