En este POST vamos a ver cómo podemos convertir un elemento de base64 a su fichero correspondiente (base64 a PDF,base64 a Excel,base64 a Word,…etc).
¿Qué es un elemento de base64?
Base64 es un algoritmo de codificación que permite transformar cualquier carácter de cualquier idioma en un alfabeto que consta de letras, dígitos y signos latinos.Podemos convertir caracteres especiales de otros idiomas como logogramas chinos, emojis e incluso imágenes en una secuencia “legible” (para cualquier ordenador), que se puede guardar y/o transferir en cualquier otro lugar.
A menudo se utiliza para transmitir datos binarios por medio de transmisiones que tratan sólo con texto, como para enviar imágenes y archivos adjuntos por correo electrónico.
Paso 1: Convertimos los bits de base64 a un Array
Partimos que tenemos en algún lugar el elemento de base64 (por base de datos, API, etc). Se representa como un elemento de texto (técnicamente string) Por ejemplo:
Este documento pdf en base64 es el siguiente código:
JVBERi0xLjQKJdPr6eEKMSAwIG9iago8PC9UaXRsZSA8RkVGRjAwNDQwMDZGMDA2MzAwNzUwMDZEMDA2NTAwNkUwMDc0MDA2RjAwMjAwMDczMDA2OTAwNkUwMDIwMDA3NDAwRUQwMDc0MDA3NTAwNkMwMDZGPgovUHJvZHVjZXIgKFNraWEvUERGIG0xMTAgR29vZ2xlIERvY3MgUmVuZGVyZXIpPj4KZW5kb2JqCjMgMCBvYmoKPDwvY2EgMQovQk0gL05vcm1hbD4+CmVuZG9iago1IDAgb2JqCjw8L0ZpbHRlciAvRmxhdGVEZWNvZGUKL0xlbmd0aCAyMDE+PiBzdHJlYW0KeJyVUUEKwjAQvO8r9gOm2WTTTUAEFduzkh+oLQg9WP8PJm21IORgNiRhhpnJJoQ61YbS4tngdYAnKHET+tkTSJjr0uJ8GHuoWov9CzIvgZHIWBzv0MH5x0FMnsljURwiVE0SsKrzEIwd0HoLxRI8iQ0YB8iYVUbEsvUYb7jVmpsdxgck2NXEwSbNQvBEeEWOSItfiXoiRFnjybgv7kxJICXiWMreFxTFDDdnsNJCQZysVv7PNop9E5Ui/n0QpyfiFNPvvgFYh3ReCmVuZHN0cmVhbQplbmRvYmoKMiA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MTIKL1Jvb3QgNyAwIFIKL0luZm8gMSAwIFI+PgpzdGFydHhyZWYKMTIzMDQKJSVFT0Y=
Vamos a convertir este string de base64 a un array, y lo haremos con esta función:
public base64ToArrayBuffer(base64String: string){
let binaryString = window.atob(base64String);
let binaryLength = binaryString.length;
let bytes = new Uint8Array(binaryLength);
for (let i=0; i
Paso 2: Convertimos el elemento de base64 a un fichero:
[icon name="triangle-exclamation" prefix="fas"] Atención : Hay que seguir el paso anterior, ya que se utiliza la función base64ToArrayBuffer en la función que vamos a mostrar.
En la función se crea un diccionario documentTypeAvailable
para añadir las extensiones que vamos a usar en nuestro proyecto y poder reutilizar esta función. Más abajo de este artículo os dejo dos tablas con las extensiones más utilizadas.
¿Qué hace blob?
Representa un objeto tipo fichero de datos planos inmutables. Los Blobs representan datos que no necesariamente se encuentran en un formato nativo de JavaScript. La interfaz File
se encuentra basada en un Blob
, heredando y expendiendo la funcionalidad de un Blob
para soportar archivos en el sistema del usuario.
public downloadDocument (filename: string, documentType: string, base64String: string): void {
let documentTypeAvailable = new Map();
documentTypeAvailable.set('excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
documentTypeAvailable.set('word','application/vnd.openxmlformats-officedocument.wordprocessingml.document');
documentTypeAvailable.set('pdf','');
let bytes = this.base64ToArrayBuffer(base64String)
let blob = new Blob([bytes], { type: documentTypeAvailable.get(documentType)});
let objURL : string = URL.createElement('a') as HTMLAnchorElement;
a.href = objURL;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(objURL);
}
Tipos de MIME genéricos
Extensión | Tipo de MIME |
Texto plano | text/plain |
.xml | text/xml |
application/pdf | |
.zip | application/zip, application/octet-stream, application/x-zip-compressed, multipart/x-zip |
.rar | application/vnd.rar, application/x-rar-compressed, application/octet-stream |
Tipos de MIME del paquete de Microsoft Office
Extensión | Tipo de MIME |
.doc | application/msword |
.dot | application/msword |
.docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document |
.dotx | application/vnd.openxmlformats-officedocument.wordprocessingml.template |
.docm | application/vnd.ms-word.document.macroEnabled.12 |
.dotm | application/vnd.ms-word.template.macroEnabled.12 |
.xls | application/vnd.ms-excel |
.xlt | application/vnd.ms-excel |
.xla | application/vnd.ms-excel |
.xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
.xltx | application/vnd.openxmlformats-officedocument.spreadsheetml.template |
.xlsm | application/vnd.ms-excel.sheet.macroEnabled.12 |
.xltm | application/vnd.ms-excel.template.macroEnabled.12 |
.xlam | application/vnd.ms-excel.addin.macroEnabled.12 |
.xlsb | application/vnd.ms-excel.sheet.binary.macroEnabled.12 |
.ppt | application/vnd.ms-powerpoint |
.pot | application/vnd.ms-powerpoint |
.pps | application/vnd.ms-powerpoint |
.ppa | application/vnd.ms-powerpoint |
.pptx | application/vnd.openxmlformats-officedocument.presentationml.presentation |
.potx | application/vnd.openxmlformats-officedocument.presentationml.template |
.ppsx | application/vnd.openxmlformats-officedocument.presentationml.slideshow |
.ppam | application/vnd.ms-powerpoint.addin.macroEnabled.12 |
.pptm | application/vnd.ms-powerpoint.presentation.macroEnabled.12 |
.potm | application/vnd.ms-powerpoint.presentation.macroEnabled.12 |
.ppsm | application/vnd.ms-powerpoint.slideshow.macroEnabled.12 |
Paso 3: Llamemos a downloadDocument
this.downloadDocument('lacodigoteca','pdf','aqui ponemos el string de base64')
¡Listo! ya tenemos nuestro fichero que hemos convertido de base64 a la extensión que necesitemos.
[icon name="triangle-exclamation" prefix="fas"] Atención : Si la base64 es de un PDF, no podemos convertirlo a otra extensión como un documento Excel o Word.
Si os ha gustado este artículo, os dejo más sobre Angular 😉