Implementing Base64 encoders with JavaScript

Source: Internet
Author: User
Tags base64


Previous words


Base-64, as a common coding function, has been widely used in Basic authentication, Digest authentication, and some HTTP extensions. In the front-end domain, images are often converted to base-64 encoding for transmission over the network. In this paper, the principle of Base64 and the process of realizing Base64 encoder with JS are introduced in detail.





Principle


BASE-64 encoding converts any set of bytes into a long, common sequence of text characters that can legitimately be used as the header field value. BASE-64 encoding converts user input or binary data into a secure format that is sent as the value of the HTTP header field without worrying about the inclusion of colons, newline characters, or binary values that would break the HTTP parser



BASE-64 encoding is developed as part of the MIME multimedia e-mail standard, so that MIME can transfer rich text and arbitrary binary data between different legitimate e-mail gateways. BASE-64 encoding is similar in nature to the uuencode and BinHex standards for textual representation of binary data, but is more space efficient



"Split"



The BASE-64 encoding splits a 8-byte sequence into 6-bit fragments and assigns one character to each 6-bit fragment, which is one of the 64 characters in the Base-64 alphabet. These 64 output characters are common and can be safely placed in the HTTP header field. These 64 characters contain uppercase and lowercase letters, numbers, + and/, and special characters are used =



The following table Base-64 the alphabet


0   A   8    I   16   Q   24   Y   32   g   40   o   48   w   56   4
1    B    9     J    17    R    25    Z    33    h    41    p    49    x    57    5
2    C    10    K    18    S    26    a    34    i    42    q    50    y    58    6
3    D    11    L    19    T    27    b    35    j    43    r    51    z    59    7
4    E    12    M    20    U    28    c    36    k    44    s    52    0    60    8
5    F    13    N    21    V    29    d    37    l    45    t    53    1    61    9
6    G    14    O    22    W    30    e    38    m    46    u    54    2    62    +
7    H    15    P    23    X    31    f    39    n    47    v    55    3    63    /


[note] because the BASE64 encoding uses 8-bit characters to represent 6 bits in the information, the Base-64 encoded string is approximately 33% larger than the original value



"Code Implementation"



is a simple example of Base-64 encoding. Here, a three-character input value of "ow!" is Base-64 encoded, resulting in a 4-character Base-64 encoded value "T3CH". It works according to the following method






1. String "ow!" Split into 3 8-bit bytes (0x4f, 0x77, 0x21)



2, these 3 bytes constitute a 24-bit binary value 010011110111011100100001



3. These bits are divided into 6-bit sequences 010011, 110111, 01110, 100001



4. Each 6-bit value represents a number from 0-63, corresponding to one of the 64 characters in the Base-64 alphabet. The resulting Base-64 encoded string is a 4-character string "t3ch" that can then be routed through the line as a "safe" 8-bit character, since only some of the best-ported characters (letters, numbers, etc.) are used.



Fill



The BASE-64 code receives a 8-byte sequence that divides the binary sequence stream into 6-bit blocks. Binary sequences sometimes cannot be divided exactly into 6-bit chunks, in which case the 0 bits are filled at the end of the sequence, making the length of the binary sequence a multiple of 24 (least common multiple of 6 and 8)



When you encode a populated binary string, any 6-bit groups that are fully populated (without the bits in the original data) are represented by a special 65th symbol "=". If the 6-bit group is partially populated, set the fill bit to 0



The following table shows some of the fill instances






The initial input string "a:a" is 3 bytes (24 bits). 24 is a multiple of 6 and 8, so no padding is required and the resulting BASE-64 encoded string is "ytph"



However, by adding one more character, the input string becomes 32 bits long. The next common multiple of 6 and 8 is 48, so add a 16-bit shim. The first 4 bits of the fill are mixed with the data bits. The resulting 6-bit group 01xxxx will be treated as 010000, 16 in decimal, or Base-64 encoded Q. The remaining two 6-bit groups are shim codes, denoted by "="



Note The official code of the BASE-64 code.


Application


Every picture on a webpage needs to be downloaded from an HTTP request. That's why Sprite technology



Anyway, the download of the picture always makes a request to the server, if the picture download does not make the request to the server, but can download to the local with the HTML download at the same time that is very good, and Base64 just can solve this problem



As mentioned earlier, the BASE-64 encoded string is approximately 33% larger than the original value. So, not all pictures are appropriate using BASE-64 encoding



However, if the picture is small enough and because of the special usefulness (such as tiling, etc.) cannot be made into Sprite, the reuse of the entire site is very high and will not be updated. Then using base64 encoding to transmit the picture is good steel for the blade.



For example, a background map with only 50 bytes of 2px*2px. Convert it to base64 encoding, only more than 100 characters, this conversion is undoubtedly more worthy of praise than an HTTP request



Drag the image you want to convert directly into chrome and use the source option in the console to see the base64 encoding of the image directly





String encoding


For strings, in JavaScript, there are 2 functions for decoding and encoding base64 strings, respectively: Atob () and Btoa ()



The Btoa () function can create a BASE-64 encoded ASCII string from the binary data "string", whereas the Atob () function can decode string data encoded by BASE-64.


Console.log (Btoa (' abc '));//' YWJJ ' Console.log (Atob (' ywjj '));//' abc '


Note ie9-Browser does not support



However, the above method has limitations, is unable to convert Chinese


Uncaught domexception:failed to execute ' btoa ' in ' Window ': the string to be encoded contains characters outside of the L Atin1 range.


At this point, you need to use the encoding method, first converted to BTOA () recognized characters, and then Base64 encoding, such as can use the encodeURI () method


Var str = btoa(encodeURI(‘small match ‘));
Console.log(str);//JUU1JUIwJThGJUU3JTgxJUFCJUU2JTlGJUI0
Console.log(decodeURI(atob(str)));//‘Little Match’
<p style="margin:0">Please enter the characters to be converted in the box below</p>
<textarea id="ta" cols="30" rows="10"></textarea>
<button id="btn1">Convert</button><button id="btn2">Reverse Conversion</button><br>
<p style="margin:0">The converted characters are as follows:</p>
<textarea id="result" cols="30" rows="10" readonly></textarea>
<button id="sel">Select All</button>
<button id="reset">Clear</button>
<script>
Reset.onclick = function(){history.go();}
Btn1.onclick = function(){result.value = btoa(encodeURI(ta.value));}
Btn2.onclick = function(){result.value = decodeURI(atob(ta.value));}
Sel.onclick = function(){
     Result.focus();
     Result.select();
}
</script>



Image encoding


Using the Readasdataurl () method of the file document API, you can save the file as a data URI (in BASE64 encoding) in the result property


//base64 conversion function
Function base64(file){
     If(fileData.innerHTML){
         fileData.innerHTML = ‘‘;
         Btn.style.display = ‘none‘;
     }
     If(file){
         If(/image/.test(file.type)){
           Var reader = new FileReader();
           reader.readAsDataURL(file);
           Reader.onload = function(){
               fileData.innerHTML = reader.result;
           }
         }else{
           Alert("You must select a valid image file!");
         }
     }
}


In general, the generated Base64 encoding is long, you can add a full selection of code functions


reader.onload = function(){
    fileData.innerHTML = reader.result;
    btn.style.display = ‘inline-block‘;
    btn.onclick = function(){
        fileData.focus();    
        fileData.select();
   }
}     


You can select a picture file using the file files API


//Click event substitution
targetArea.onclick = function(){file1.click();}
/ / Control selected
File1.onchange = function(){
     Var file = file1.files[0];
     Base64(file);
}


Of course, you can use the native drag and drop, to achieve the picture drag, in an area to show the effect of BASE64 encoding


targetArea.ondragenter = function(e){this.style.outline = "1px solid black";}
targetArea.ondragleave = function(e){this.style.outline = "";}
/ / drag and drop selected
targetArea.ondrop = function(e){
     e = e || event;
     This.style.outline = "";
     Var file = e.dataTransfer.files[0];
     Base64(file);
}


The following code does not work in the Ie9-browser due to the compatibility limit of the file API


<input id="file1" type="file" accept="image/gif,image/jpeg,image/jpg,image/png,image/x-icon" style="display:none">
<div id="targetArea" style="display:inline-block;vertical-align:middle;height:100px;line-height:50px;width:210px;background:lightblue;">Drag and drop image files into this area Inside <br> or click on the area to select a local file</div>
<textarea id="fileData" style="vertical-align:middle;width:400px;height:200px;overflow:auto;word-wrap: break-word;"></textarea>
<button id="btn" style="display:none;position:absolute;margin:220px 0 0 -80px">Select All Code</button>
<script>
//base64 conversion function
Function base64(file){
    If(fileData.innerHTML){
        fileData.innerHTML = ‘‘;
        Btn.style.display = ‘none‘;
    }
    If(file){
        If(/image/.test(file.type)){
          Var reader = new FileReader();
          reader.readAsDataURL(file);
          Reader.onload = function(){
              fileData.innerHTML = reader.result;
              Btn.style.display = ‘inline-block‘;
              Btn.onclick = function(){
                  fileData.focus();
                  fileData.select();
             }
          }
        }else{
          Alert("You must select a valid image file!");
        }
    }
}
//Click event substitution
targetArea.onclick = function(){file1.click();}
/ / Control selected
File1.onchange = function(){
    Var file = file1.files[0];
    Base64(file);
}
//compatible event handler
Function addEvent(target,type,handler){
    If(target.addEventListener){
        target.addEventListener(type,handler,false);
    }else{
        target.attachEvent(‘on‘+type,function(event){
            Return handler.call(target, event);
        });
    }
}
//compatible to block default events
Function preventDefault(e){
    e = e || event;
    If(e.preventDefault){
        e.preventDefault();
    }else{
        e.returnValue = false;
    }
}
addEvent(document, ‘dragover‘, preventDefault);
addEvent(document, ‘drop‘, preventDefault);
addEvent(targetArea, ‘dragenter‘, preventDefault);
addEvent(targetArea, ‘dragover‘, preventDefault);
addEvent(targetArea, ‘dragleave‘, preventDefault);
addEvent(targetArea, ‘drop‘, preventDefault);
targetArea.ondragenter = function(e){this.style.outline = "1px solid black";}
targetArea.ondragleave = function(e){this.style.outline = "";}
/ / drag and drop selected
targetArea.ondrop = function(e){
    e = e || event;
    This.style.outline = "";
    Var file = e.dataTransfer.files[0];
    Base64(file);
}
</script> 





Implementing Base64 encoders with JavaScript


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.