js实现base64的转化

本文实现的功能:

一、前言

1、字符串转base64。

2、base64转字符串。

3、input file选择的图片转base64。

4、input file选择图片在线预览。

5、input file 修改上传类型。

 

二、插件

插件所在github地址:https://github.com/hushaohhy/base64

将base64之间的转化封装成了插件如下:

js插件代码:

// 自定义一个类(构造函数)
function Base64() {
    // 自定义对象
    this._keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    this._utf8_encode = function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }
        return utftext;
    }
    this._utf8_decode = function (utftext) {
        var string = "";
        var i = 0;
        var c , c3 , c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }

    // 定义字符串转base64的方法
    this.strToBase64 = function (str) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
        str = this._utf8_encode(str);
        while (i < str.length) {
            chr1 = str.charCodeAt(i++);
            chr2 = str.charCodeAt(i++);
            chr3 = str.charCodeAt(i++);
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
            output = output +
                this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
                this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    }

    // 定义base64转字符串的方法
    this.base64ToStr = function (base64) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        base64 = base64.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < base64.length) {
            enc1 = this._keyStr.indexOf(base64.charAt(i++));
            enc2 = this._keyStr.indexOf(base64.charAt(i++));
            enc3 = this._keyStr.indexOf(base64.charAt(i++));
            enc4 = this._keyStr.indexOf(base64.charAt(i++));
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
            output = output + String.fromCharCode(chr1);
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = this._utf8_decode(output);
        return output;
    }

    // 定义图片转base64的方法(FileReader的方法)
    this.imgToBase64FR = function (obj) {
        var reader = new FileReader();
        var imgFile = obj.imgFile;// 图片文件
        var size = parseInt(obj.size)*1024*1024;// 限制的上传文件的大小,单位:B(字节)
        // var imgUrlBase64 = null;
        if(imgFile) {
            //将文件以Data URL形式读入页面
            reader.readAsDataURL(imgFile);
            reader.onload = function (e) {
                if (size != 0 && size < reader.result.length) {
                    obj.success({
                        "flag":100
                    })
                    return;
                }else{
                    //执行上传操作
                    obj.success({
                        "flag":101,
                        "data":reader.result
                    })
                }
            }
        }

    }
    
    // 定义图片转base64的方法(canvas的方法)
    this.imgToBase64Canvas = function (obj) {
        if(obj.imgFile) {
            var size = parseInt(obj.size)*1024*1024;// 限制的上传文件的大小,单位:B(字节)
            if (size != 0 && size < obj.imgFile.size) {
                obj.success({
                    "flag":100
                })
                return;
            }
            var imgurl = window.URL.createObjectURL(obj.imgFile); // 将文件创建url
            // var image = document.createElement('img');
            var image = new Image();// 创建一个图片对象
            image.src = imgurl;// 对图片绑定src
            // 当图片加载完毕后执行的方法,必须加这个,否则返回的图片width和height为0
            image.onload = function() {
                var img = image;
                var canvas = document.createElement("canvas");
                canvas.width = img.width;
                canvas.height = img.height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(img, 0, 0, img.width, img.height);
                var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
                var dataURL = canvas.toDataURL("image/"+ext);
                canvas = null;// 释放
                // 返回base64
                obj.success({
                    "flag":101,
                    "data":dataURL
                })
            }
        }
    }
}

html代码:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>base64之间的相互转化</title>
</head>
<body>
<input type="file" id="img" accept="image/*">
<div class="preview">
    预览区域:
    <img src="" alt="">
</div>
</body>
</html>
<script type="text/javascript" src="../js/base64.js"></script>
<script>
   window.onload = function () {
       var base64obj = new Base64();// 实例化对象
       var base64Str = base64obj.strToBase64("今天是周三?");// 字符串转base64
       console.log(base64Str)
       var str = base64obj.base64ToStr(base64Str)// base64转字符串
       console.log(str);
       var img = document.getElementById("img")
       var imgBase64 = null;
       img.onchange = function () {
           var _this = this;
           console.log(_this.files[0])
           base64obj.imgToBase64FR({
               "imgFile":_this.files[0],// 选择的图片文件
               "size":2,// 上传图片的最大大小,单位是M,即2M
               "success":function (res) {
                   if(res.flag == 100) {
                       console.log("上传的图片超过设定的最大大小")
                   }else if(res.flag == 101) {
                       console.log("base64图片为:",res.data)
                       var preview = document.querySelector(".preview img");
                       preview.src = res.data
                   }
               }// 成功的回调函数
           })

           /*base64obj.imgToBase64Canvas({
               "imgFile":_this.files[0],// 选择的图片文件
               "size":2,// 上传图片的最大大小,单位是M,即2M
               "success":function (res) {
                   if(res.flag == 100) {
                       console.log("上传的图片超过设定的最大大小")
                   }else if(res.flag == 101) {
                       console.log("base64图片为:",res.data)
                   }
               }// 成功的回调函数
           })*/
       }
   }
</script>

以上实现了:字符串和base64之间的相互转化,图片转base64。

需要注意的是:由于用到了FileReader和Canvas,因此代码对不支持这两种的浏览器不兼容。

三、图片预览

在本页上传图片进行预览的功能原理:

将图片转化的base64代码显示到img标签中。

var preview = document.querySelector(".preview img");
preview.src = res.data// res.data是图片转的base64代码

四、input file的上传类型

<input type="file" id="img" accept="image/*">

这是支持的文件类型(从网上找的,没有一个个测验,慎用

*.3gpp  audio/3gpp, video/3gpp  3GPP Audio/Video
*.ac3   audio/ac3   AC3 Audio
*.asf   allpication/vnd.ms-asf  Advanced Streaming Format
*.au    audio/basic AU Audio
*.css   text/css    Cascading Style Sheets
*.csv   text/csv    Comma Separated Values
*.doc   application/msword  MS Word Document
*.dot   application/msword  MS Word Template
*.dtd   application/xml-dtd Document Type Definition
*.dwg   image/vnd.dwg   AutoCAD Drawing Database
*.dxf   image/vnd.dxf   AutoCAD Drawing Interchange Format
*.gif   image/gif   Graphic Interchange Format
*.htm   text/html   HyperText Markup Language
*.html  text/html   HyperText Markup Language
*.jp2   image/jp2   JPEG-2000
*.jpe   image/jpeg  JPEG
*.jpeg  image/jpeg  JPEG
*.jpg   image/jpeg  JPEG
*.js    text/javascript, application/javascript JavaScript
*.json  application/json    JavaScript Object Notation
*.mp2   audio/mpeg, video/mpeg  MPEG Audio/Video Stream, Layer II
*.mp3   audio/mpeg  MPEG Audio Stream, Layer III
*.mp4   audio/mp4, video/mp4    MPEG-4 Audio/Video
*.mpeg  video/mpeg  MPEG Video Stream, Layer II
*.mpg   video/mpeg  MPEG Video Stream, Layer II
*.mpp   application/vnd.ms-project  MS Project Project
*.ogg   application/ogg, audio/ogg  Ogg Vorbis
*.pdf   application/pdf Portable Document Format
*.png   image/png   Portable Network Graphics
*.pot   application/vnd.ms-powerpoint   MS PowerPoint Template
*.pps   application/vnd.ms-powerpoint   MS PowerPoint Slideshow
*.ppt   application/vnd.ms-powerpoint   MS PowerPoint Presentation
*.rtf   application/rtf, text/rtf   Rich Text Format
*.svf   image/vnd.svf   Simple Vector Format
*.tif   image/tiff  Tagged Image Format File
*.tiff  image/tiff  Tagged Image Format File
*.txt   text/plain  Plain Text
*.wdb   application/vnd.ms-works    MS Works Database
*.wps   application/vnd.ms-works    Works Text Document
*.xhtml application/xhtml+xml   Extensible HyperText Markup Language
*.xlc   application/vnd.ms-excel    MS Excel Chart
*.xlm   application/vnd.ms-excel    MS Excel Macro
*.xls   application/vnd.ms-excel    MS Excel Spreadsheet
*.xlt   application/vnd.ms-excel    MS Excel Template
*.xlw   application/vnd.ms-excel    MS Excel Workspace
*.xml   text/xml, application/xml   Extensible Markup Language
*.zip   aplication/zip  Compressed Archive

通过修改accept的值,仅仅是修改了选择的显示类型,并不代表不能选择其他类型。

真正的限制上传类型,还需要通过代码判断文件类型进行筛选。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值