Open hemanth opened 4 days ago
Are you aware of the Uint8Array to/from base64 and hex proposal?
Yes @tomayac that proposal from TC39 did cross my mind.
fileToBase64 & urlToBase64 is seeking to solve file or URL to base64 without any extra steps for the API consumers.
I suggest renaming it to blobToBase64 and textToBase64
Introduction
Modern web applications frequently require conversion of file contents (such as images, videos, or documents) or URLs pointing to such resources into Base64-encoded strings. Currently, developers rely on various workarounds involving
FileReader
orfetch
APIs to achieve this, leading to inconsistencies and complex code structures. We propose introducing a standardizedwindow.fileToBase64
API to streamline the conversion of files and URLs to Base64, reducing developer overhead and providing a more secure, consistent, and efficient method for web applications.Use Cases
Goals
FileReader
orfetch
workarounds.Non-goals
Proposed Solution
We propose the introduction of
window.fileToBase64
andwindow.urlToBase64
methods. These functions will allow developers to convert files and URLs into Base64 strings seamlessly.Method Definitions
window.fileToBase64(file: File): Promise<string>
File
object and returns a Promise that resolves to a Base64 string of the file content.window.urlToBase64(url: string): Promise<string>
Example API Usage
Encoding a Local File
Encoding a URL
Examples
Example 1: Profile Picture Upload
A user uploads an image to set as their profile picture. Using
fileToBase64
, the image is encoded and then displayed inline, before uploading it as a Base64 string.Example 2: Offline PDF Storage
An offline document viewer in a PWA fetches a document from a URL and uses
urlToBase64
to store the document as Base64 inlocalStorage
for later access.Alternate Approaches
Existing solutions involve
FileReader
for local files andfetch
for URLs. However, these approaches lack the consistency, built-in security measures, and ease of use a dedicated API could provide. Standardizing an approach onwindow
allows consistent, optimized functionality directly within the browser context, addressing the shortcomings of ad hoc methods.Privacy & Security Considerations
urlToBase64
method should respect CORS policies to prevent unauthorized access to restricted resources.After careful review, no additional privacy or security concerns are expected, but community feedback is encouraged.
Let’s Discuss
fileToBase64
andurlToBase64
clear and suitable names?btoa
to support file and URL encoding could indeed simplify this proposal?