本文实现的功能:
一、前言
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代码:
base64之间的相互转化
预览区域:
以上实现了:字符串和base64之间的相互转化,图片转base64。
需要注意的是:由于用到了FileReader和Canvas,因此代码对不支持这两种的浏览器不兼容。
三、图片预览
在本页上传图片进行预览的功能原理:
将图片转化的base64代码显示到img标签中。
var preview = document.querySelector(".preview img");
preview.src = res.data// res.data是图片转的base64代码
四、input file的上传类型
这是支持的文件类型(从网上找的,没有一个个测验,慎用)
*.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的值,仅仅是修改了选择的显示类型,并不代表不能选择其他类型。
真正的限制上传类型,还需要通过代码判断文件类型进行筛选。