本文实现的功能:
一、前言
1、字符串转base64。
2、base64转字符串。
3、input file选择的图片转base64。
4、input file选择图片在线预览。
5、input file 修改上传类型。
二、插件
插件所在github地址:/hushaohhy/base64
将base64之间的转化封装成了插件如下:
js插件代码:
// 自定义一个类(构造函数)
function Base64() {
// 自定义对象
this._keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
this._utf8_encode = function (string) {
string = (/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < ; n++) {
var c = (n);
if (c < 128) {
utftext += (c);
} else if((c > 127) && (c < 2048)) {
utftext += ((c >> 6) | 192);
utftext += ((c & 63) | 128);
} else {
utftext += ((c >> 12) | 224);
utftext += (((c >> 6) & 63) | 128);
utftext += ((c & 63) | 128);
}
}
return utftext;
}
this._utf8_decode = function (utftext) {
var string = "";
var i = 0;
var c , c3 , c2 = 0;
while ( i < ) {
c = (i);
if (c < 128) {
string += (c);
i++;
} else if((c > 191) && (c < 224)) {
c2 = (i+1);
string += (((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = (i+1);
c3 = (i+2);
string += (((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 < ) {
chr1 = (i++);
chr2 = (i++);
chr3 = (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 = (/[^A-Za-z0-9\+\/\=]/g, "");
while (i < ) {
enc1 = this._keyStr.indexOf((i++));
enc2 = this._keyStr.indexOf((i++));
enc3 = this._keyStr.indexOf((i++));
enc4 = this._keyStr.indexOf((i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + (chr1);
if (enc3 != 64) {
output = output + (chr2);
}
if (enc4 != 64) {
output = output + (chr3);
}
}
output = this._utf8_decode(output);
return output;
}
// 定义图片转base64的方法(FileReader的方法)
this.imgToBase64FR = function (obj) {
var reader = new FileReader();
var imgFile = ;// 图片文件
var size = parseInt()*1024*1024;// 限制的上传文件的大小,单位:B(字节)
// var imgUrlBase64 = null;
if(imgFile) {
//将文件以Data URL形式读入页面
(imgFile);
= function (e) {
if (size != 0 && size < ) {
({
"flag":100
})
return;
}else{
//执行上传操作
({
"flag":101,
"data":
})
}
}
}
}
// 定义图片转base64的方法(canvas的方法)
this.imgToBase64Canvas = function (obj) {
if() {
var size = parseInt()*1024*1024;// 限制的上传文件的大小,单位:B(字节)
if (size != 0 && size < ) {
({
"flag":100
})
return;
}
var imgurl = (); // 将文件创建url
// var image = ('img');
var image = new Image();// 创建一个图片对象
= imgurl;// 对图片绑定src
// 当图片加载完毕后执行的方法,必须加这个,否则返回的图片width和height为0
= function() {
var img = image;
var canvas = ("canvas");
= ;
= ;
var ctx = ("2d");
(img, 0, 0, , );
var ext = ((".")+1).toLowerCase();
var dataURL = ("image/"+ext);
canvas = null;// 释放
// 返回base64
({
"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" accept="image/*">
<div class="preview">
预览区域:
<img src="" alt="">
</div>
</body>
</html>
<script type="text/javascript" src="../js/"></script>
<script>
= function () {
var base64obj = new Base64();// 实例化对象
var base64Str = base64obj.strToBase64("今天是周三?");// 字符串转base64
(base64Str)
var str = base64obj.base64ToStr(base64Str)// base64转字符串
(str);
var img = ("img")
var imgBase64 = null;
= function () {
var _this = this;
(_this.files[0])
base64obj.imgToBase64FR({
"imgFile":_this.files[0],// 选择的图片文件
"size":2,// 上传图片的最大大小,单位是M,即2M
"success":function (res) {
if( == 100) {
("上传的图片超过设定的最大大小")
}else if( == 101) {
("base64图片为:",)
var preview = (".preview img");
=
}
}// 成功的回调函数
})
/*base64obj.imgToBase64Canvas({
"imgFile":_this.files[0],// 选择的图片文件
"size":2,// 上传图片的最大大小,单位是M,即2M
"success":function (res) {
if( == 100) {
("上传的图片超过设定的最大大小")
}else if( == 101) {
("base64图片为:",)
}
}// 成功的回调函数
})*/
}
}
</script>
以上实现了:字符串和base64之间的相互转化,图片转base64。
需要注意的是:由于用到了FileReader和Canvas,因此代码对不支持这两种的浏览器不兼容。
三、图片预览
在本页上传图片进行预览的功能原理:
将图片转化的base64代码显示到img标签中。
var preview = (".preview img");
= // 是图片转的base64代码
四、input file的上传类型
<input type="file" accept="image/*">
这是支持的文件类型(从网上找的,没有一个个测验,慎用)
*.3gpp audio/3gpp, video/3gpp 3GPP Audio/Video
*.ac3 audio/ac3 AC3 Audio
*.asf allpication/-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/ AutoCAD Drawing Database
*.dxf image/ 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/-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/-powerpoint MS PowerPoint Template
*.pps application/-powerpoint MS PowerPoint Slideshow
*.ppt application/-powerpoint MS PowerPoint Presentation
*.rtf application/rtf, text/rtf Rich Text Format
*.svf image/ Simple Vector Format
*.tif image/tiff Tagged Image Format File
*.tiff image/tiff Tagged Image Format File
*.txt text/plain Plain Text
*.wdb application/-works MS Works Database
*.wps application/-works Works Text Document
*.xhtml application/xhtml+xml Extensible HyperText Markup Language
*.xlc application/-excel MS Excel Chart
*.xlm application/-excel MS Excel Macro
*.xls application/-excel MS Excel Spreadsheet
*.xlt application/-excel MS Excel Template
*.xlw application/-excel MS Excel Workspace
*.xml text/xml, application/xml Extensible Markup Language
*.zip aplication/zip Compressed Archive
通过修改accept的值,仅仅是修改了选择的显示类型,并不代表不能选择其他类型。
真正的限制上传类型,还需要通过代码判断文件类型进行筛选。