Base64 encoding for html

Data URLs

Data URLs, URLs prefixed with the data: scheme, allow content creators to embed small files inline in documents. They were formerly known as «data URIs» until that name was retired by the WHATWG.

Note: Data URLs are treated as unique opaque origins by modern browsers, rather than inheriting the origin of the settings object responsible for the navigation.

Syntax

Data URLs are composed of four parts: a prefix ( data: ), a MIME type indicating the type of data, an optional base64 token if non-textual, and the data itself:

The mediatype is a MIME type string, such as ‘image/jpeg’ for a JPEG image file. If omitted, defaults to text/plain;charset=US-ASCII

If the data contains characters defined in RFC 3986 as reserved characters, or contains space characters, newline characters, or other non-printing characters, those characters must be URL encoded (aka «URL encoded»).

If the data is textual, you can embed the text (using the appropriate entities or escapes based on the enclosing document’s type). Otherwise, you can specify base64 to embed base64-encoded binary data. You can find more info on MIME types here and here.

The text/plain data Hello, World! . Note how the comma is URl encoded as %2C , and the space character as %20 .

base64-encoded version of the above

An HTML document with

Hello, World!

An HTML document with that executes a JavaScript alert. Note that the closing script tag is required.

Encoding data into base64 format

Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. By consisting only of ASCII characters, base64 strings are generally url-safe, and that’s why they can be used to encode data in Data URLs.

Encoding in JavaScript

The Web APIs have native methods to encode or decode to base64: Base64.

Encoding on a Unix system

Base64 encoding of a file or string on Linux and macOS systems can be achieved using the command-line base64 (or, as an alternative, the uuencode utility with -m argument).

echo -n hello|base64 # outputs to console: aGVsbG8= echo -n hello>a.txt base64 a.txt # outputs to console: aGVsbG8= base64 a.txt>b.txt # outputs to file b.txt: aGVsbG8= 

Encoding on Microsoft Windows

On Windows, Convert.ToBase64String from PowerShell can be used to perform the Base64 encoding:

[convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("hello")) # outputs to console: aGVsbG8=

Alternatively, a GNU/Linux shell (such as WSL) provides the utility base64 :

echo -n hello | base64 # outputs to console: aGVsbG8= 

Common problems

This section describes problems that commonly occur when creating and using data URLs.

p>a name%3D"bottom">bottoma>?arg=valp> 

This represents an HTML resource whose contents are:

p>a name="bottom">bottoma>?arg=valp> 

The format for data URLs is very simple, but it’s easy to forget to put a comma before the «data» segment, or to incorrectly encode the data into base64 format.

A data URL provides a file within a file, which can potentially be very wide relative to the width of the enclosing document. As a URL, the data should be formattable with whitespace (linefeed, tab, or spaces), but there are practical issues that arise when using base64 encoding.

Browsers are not required to support any particular maximum length of data. For example, the Opera 11 browser limited URLs to 65535 characters long which limits data URLs to 65529 characters (65529 characters being the length of the encoded data, not the source, if you use the plain data: , without specifying a MIME type). Firefox version 97 and newer supports data URLs of up to 32MB (before 97 the limit was close to 256MB). Chromium objects to URLs over 512MB, and Webkit (Safari) to URLs over 2048MB.

Invalid parameters in media, or typos when specifying ‘base64’ , are ignored, but no error is provided.

No support for query strings, etc.

The data portion of a data URL is opaque, so an attempt to use a query string (page-specific parameters, with the syntax ?parameter-data ) with a data URL will just include the query string in the data the URL represents.

A number of security issues (for example, phishing) have been associated with data URLs, and navigating to them in the browser’s top level. To mitigate such issues, top-level navigation to data: URLs is blocked in all modern browsers. See this blog post from the Mozilla Security Team for more details.

Specifications

Browser compatibility

BCD tables only load in the browser

Источник

How to Display Base64 Images in HTML

Base64 encoding and Data URL go hand-in-hand, as Data URLs reduce the number of HTTP requests that are needed for the browser to display an HTML document.

In this snippet, we’ll demonstrate how you can display Base64 images in HTML.

How to Use the Tag

The tag has a src attribute and contains the Data URL of the image. A Data URL is composed of two parts, which are separated by a comma. The first part specifies a Base64 encoded image, and the second part specifies the Base64 encoded string of the image. Add also an alt attribute.

img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4 //8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

Now, see the full code, where we need to place the tag presented above within a element.

Example of embedding a Base64 encoded image into HTML:

html> html> head> title>Title of the document title> head> body> div> p>From wikipedia p> img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4 //8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" /> div> body> html>

Convert your image to a Base64 string

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>Image to Base64 title> head> body> input type="file" id="inputImage" accept="image/*"> textarea id="outputBase64" rows="10" cols="80" readonly> textarea> script> document.getElementById('inputImage').addEventListener('change', function(event) < const file = event.target.files[0]; const reader = new FileReader(); reader.onloadend = function( ) < const base64 = reader.result; document.getElementById('outputBase64').value = base64; >; reader.readAsDataURL(file); >); script> body> html>

Источник

How to Encode and Decode HTML Base64 using JavaScript – JS Encoding Example

Joel Olawanle

Joel Olawanle

How to Encode and Decode HTML Base64 using JavaScript – JS Encoding Example

When building an application or writing a program, you may need to encode or decode with HTML Base64 in JavaScript.

This is possible thanks to two Base64 helper functions that are part of the HTML specification and are supported by all modern browsers.

In this article, you will learn about Base64 and how it works to convert binary data, regular strings, and lots more into ASCII text.

What is Base64?

Base64 is a group of binary-to-text encoding schemes representing binary data in ASCII string format. It is commonly used to encode data that needs to be stored or transmitted in a way that cannot be directly represented as text.

Base64 encoding works by mapping binary data to 64 characters from the ASCII character set. The 64 characters used in Base64 encoding are: A-Z , a-z , 0-9 , + , and / .

The encoding process takes 3 bytes of binary data and maps it to 4 characters from the above set, such that a single character represents every 6 bits of binary data. The result is a string of ASCII characters that can be transmitted or stored as text.

Base64 decoding is the reverse process of encoding. It takes a Base64 encoded string and maps each character back to its 6-bit binary representation. The resulting binary data is a reconstruction of the original binary data encoded to Base64.

How to Encode and Decode HTML Base64 using JavaScript

To encode and decode in JavaScript, you will use the btoa() and atob() JavaScript functions that are available and supported by modern web browsers.

These JavaScript helper functions are named after old Unix commands for converting binary to ASCII (btoa) and ASCII to binary (atob).

You can encode a string to base64 in JavaScript using the btoa() function and decode a base64 string using atob() function. For example, if you have a string stored in a variable, as seen below, you can first encode it to Base64:

let myString = "Welcome to freeCodeCamp!"; let encodedValue = btoa(myString); console.log(encodedValue); // V2VsY29tZSB0byBmcmVlQ29kZUNhbXAh 

You can also decode the encodedValue back to its original form using the atob() function. This function takes the encoded value and decodes it from Base64:

let myString = "Welcome to freeCodeCamp!"; let encodedValue = btoa(myString); let decodedValue = atob(encodedValue); console.log(decodedValue); // Welcome to freeCodeCamp! 

You now know how to encode and decode Base64 in JavaScript.

More JavaScript Encoding Examples

You can also encode binary data to Base64 encoded ASCII text in JavaScript using the btoa() function:

let binaryData = new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]); let stringValue = String.fromCharCode.apply(null, binaryData); console.log(stringValue); // "Hello World" let encodedValue = btoa(stringValue); console.log(encodedValue); // SGVsbG8gV29ybGQ= 

In the above, you first converted Unicode values to characters and then encoded the string.

You can also decode the Base64 encoded ASCII text to binary data in JavaScript using the atob() function:

let encodedValue = "SGVsbG8gV29ybGQ="; let binaryData = new Uint8Array(atob(encodedValue).split("").map(function (c) < return c.charCodeAt(0); >)); console.log(binaryData); // Uint8Array [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] 

Wrapping Up!

In this article, you have learned what Base64 means, how it works, and when to encode and decode in JavaScript.

Base64 is not intended to be a secure encryption method, nor is it intended to be a compression method, because encoding a string to Base64 typically results in a 33% longer output.

Base64 encoding is commonly used in JavaScript for situations like:

  • Storing and transmitting binary data as text.
  • Encrypting data where the encoded data is sent over an insecure channel and decoded on the other end. However, it should not be considered a secure encryption method, as it can easily be decoded.
  • Data transfer between systems with different character sets.
  • Storing binary data in a database.

Thanks for reading and have fun coding!

You can access over 185 of my articles by visiting my website. You can also use the search field to see if I’ve written a specific article.

Источник

Читайте также:  One dark css themes
Оцените статью