Function getBase64

  • Converts a file to its base64 representation.

    Parameters

    • file: File

      The file to convert.

    Returns Promise<string>

    A promise that resolves to the base64 representation of the file as a string.

    // Example 1: Convert an image file to base64
    const fileInput = document.querySelector<HTMLInputElement>('#fileInput');
    if (fileInput?.files?.[0]) {
    getBase64(fileInput.files[0])
    .then((base64) => {
    console.log('Base64 representation:', base64);
    })
    .catch((error) => {
    console.error('Error converting file to base64:', error);
    });
    }
    // Example 2: Handling errors
    const file = new File(['invalid-content'], 'test.txt', { type: 'text/plain' });
    getBase64(file)
    .then((base64) => {
    console.log('Base64:', base64);
    })
    .catch((error) => {
    console.error('Failed to convert file:', error.message);
    });