Harnessing the Magic of Base64: Converting Images and PDFs with Ease
In today’s digital landscape, the ability to seamlessly handle multimedia files is crucial for web developers. Enter Base64 encoding — a powerful technique that transforms binary data into text strings, opening the door to a myriad of possibilities.
In this tutorial, we’ll explore how to leverage Base64 encoding to convert images and PDFs into easily manageable strings. Using Angular and JavaScript, we’ll unravel the mysteries of file manipulation, empowering you to integrate this functionality into your web applications effortlessly.
In this tutorial, we’ll explore how to leverage Base64 encoding to convert images and PDFs into easily manageable strings. Using Angular and JavaScript, we’ll unravel the mysteries of file manipulation, empowering you to integrate this functionality into your web applications effortlessly.
HTML file
<input type="file" accept="image/*" (change)="imageChanged($event)"> <input type="file" accept=".pdf" (change)="pdfChanged($event)">
Function to convert image to base 64 as promise
public imageToBase64Promise(event: any): Promise<string> { const promise = new Promise<string>((resolve, reject) => { const file: File = event.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = (e: any) => { const image = new Image(); image.src = e.target.result; image.onload = () => { resolve(image.src); } image.onerror = () => { reject("Unable to convert image into base64") } } reader.readAsDataURL(file); } }); return promise; }
Function to convert PDF to base 64 as promise:
public pdfToBase64Promise(event: any): Promise<string> { const promise = new Promise<string>((resolve, reject) => { const file: File = event.target.files[0]; if (file) { const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { resolve(reader.result as string); }; reader.onerror = () =>{ reject('failed to convert pdf to base 64'); } } }); return promise; }
Ts file
public imageChanged(event: any){ this.imageToBase64Promise(event).then( (res) =>{ const imageBase64 = res; } ) } public pdfChanged(event: any){ this.pdfToBase64Promise(event).then( (res) =>{ const pdfBase64 = res; } ) }