1、文件转base64
/**
* 获取文件的Base64
* @param file {File} 文件
* @param callback {Function} 回调函数,参数为获取到的base64
*/
function fileToBase64(file, callback) {
const fileReader = new FileReader()
fileReader.readAsDataURL(file)
fileReader.onload = function () {
callback(this.result)
}
}
2、base64转blob/file
/**
* Base64转Blob
* @param dataURL {String} base64
* @param mimeType {String} [可选]文件类型,默认为base64中的类型
* @returns {Blob}
*/
function base64ToBlob(dataURL, mimeType = null) {
const arr = dataURL.split(','),
defaultMimeType = arr[0].match(/:(.*?);/)[1],
bStr = window.atob(arr[1]),
n = bStr.length,
u8arr = new Uint8Array(n);
let n = bStr.length;
while (n--) {
u8arr[n] = bStr.charCodeAt(n);
}
return new Blob([u8arr], {type: mimeType || defaultMimeType})
}
/**
* Base64转File
* @param dataURL {String} base64
* @param fileName {String} 文件名
* @param mimeType {String} [可选]文件类型,默认为base64中的类型
* @returns {File}
*/
function base64ToFile(dataURL, fileName, mimeType = null) {
const arr = dataURL.split(','),
defaultMimeType = arr[0].match(/:(.*?);/)[1],
bStr = window.atob(arr[1]),
n = bStr.length,
u8arr = new Uint8Array(n);
let n = bStr.length;
while (n--) {
u8arr[n] = bStr.charCodeAt(n);
}
return new File([u8arr], fileName, {type: mimeType || defaultMimeType})
}
/**
* Blob转File
* @param blob {Blob} blob
* @param fileName {String} 文件名
* @param mimeType {String} 文件类型
* @return {File}
*/
function blobToFile (blob, fileName, mimeType) {
return new File([blob], fileName, {type: mimeType})
}
3、图片压缩和裁剪
css属性:object-fit: container; 自适应宽高展示图片
/**
* 图片压缩和尺寸裁剪
* @param file {File} 图片文件
* @param quality {Number} 生成图片质量,0.0~1.0之间,质量越小、文件越小、图片越模糊(默认0.75)
* @param callback {Function} 回调方法,参数为原文件(小于阈值的情况下)或压缩后的新文件
* @param maxSize {Number} [可选]大小阈值,单位:KB,默认500KB, 超出则压缩
* @param targetWidth {Number} [可选]生成图片的宽度,单位:px,默认800
* @param targetHeight {Number} [可选]生成图片的高度,单位:px,默认值按宽度自适应获取
*/
function compressImg (options) {
const { file, quality = 0.75, callback, maxSize, targetWidth = 800, targetHeight = null } = options;
let sizeThreshold = 512000;
if (maxSize) {
sizeThreshold = maxSize * 1024;
}
if (!file || !callback) {
console.error('pressImg参数不完整!')
return
}
if (!file.type.includes('image')) {
console.error('文件格式非图片')
return
}
fileToBase64(file, function (base64) {
if (base64) {
const image = new Image()
image.src = base64
image.onload = function () {
if (file.size <= sizeThreshold && this.width <= targetWidth) {// 大小、宽度均小于阈值,则不需处理,返回原文件
return callback(file)
}
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
const scale = this.width / this.height
canvas.width = targetWidth
canvas.height = targetHeight || (targetWidth / scale)
context.drawImage(image, 0, 0, canvas.width, canvas.height)
const dataURL = canvas.toDataURL(file.type, quality)
const newFile = base64ToFile(dataURL, file.name)
callback(newFile)
}
}
})
}
4、数组、对象、字符串等转base64
// 数据转base64
function dataToBase64(data){
const str = JSON.stringify(data);
// 对字符串进行编码
const encode = window.encodeURIComponent(str);
// 对编码的字符串转化base64
const base64 = window.btoa(encode);
return base64;
}
// base64转数据
function base64ToData(base64){
// 解码base64
const data = window.atob(base64);
// 对解码的base64串再次进行编码
const str = window.decodeURIComponent(data);
const res = JSON.parse(str);
return res;
}
5、纯js解码base64
var Base64 = {
_keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',
encode: function (e) {
var t = '';
var n, r, i, s, o, u, a;
var f = 0;
e = Base64._utf8_encode(e);
while (f < e.length) {
n = e.charCodeAt(f++);
r = e.charCodeAt(f++);
i = e.charCodeAt(f++);
s = n >> 2;
o = ((n & 3) << 4) | (r >> 4);
u = ((r & 15) << 2) | (i >> 6);
a = i & 63;
if (isNaN(r)) {
u = a = 64;
} else if (isNaN(i)) {
a = 64;
}
t =
t +
this._keyStr.charAt(s) +
this._keyStr.charAt(o) +
this._keyStr.charAt(u) +
this._keyStr.charAt(a);
}
return t;
},
decode: function (e) {
var t = '';
var n, r, i;
var s, o, u, a;
var f = 0;
e = e.replace(/[^A-Za-z0-9+/=]/g, '');
while (f < e.length) {
s = this._keyStr.indexOf(e.charAt(f++));
o = this._keyStr.indexOf(e.charAt(f++));
u = this._keyStr.indexOf(e.charAt(f++));
a = this._keyStr.indexOf(e.charAt(f++));
n = (s << 2) | (o >> 4);
r = ((o & 15) << 4) | (u >> 2);
i = ((u & 3) << 6) | a;
t = t + String.fromCharCode(n);
if (u != 64) {
t = t + String.fromCharCode(r);
}
if (a != 64) {
t = t + String.fromCharCode(i);
}
}
t = Base64._utf8_decode(t);
return t;
},
_utf8_encode: function (e) {
e = e.replace(/rn/g, 'n');
var t = '';
for (var n = 0; n < e.length; n++) {
var r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r);
} else if (r > 127 && r < 2048) {
t += String.fromCharCode((r >> 6) | 192);
t += String.fromCharCode((r & 63) | 128);
} else {
t += String.fromCharCode((r >> 12) | 224);
t += String.fromCharCode(((r >> 6) & 63) | 128);
t += String.fromCharCode((r & 63) | 128);
}
}
return t;
},
_utf8_decode: function (e) {
var t = '';
var n = 0;
var c1, c2, c3;
var r = (c1 = c2 = 0);
while (n < e.length) {
r = e.charCodeAt(n);
if (r < 128) {
t += String.fromCharCode(r);
n++;
} else if (r > 191 && r < 224) {
c2 = e.charCodeAt(n + 1);
t += String.fromCharCode(((r & 31) << 6) | (c2 & 63));
n += 2;
} else {
c2 = e.charCodeAt(n + 1);
c3 = e.charCodeAt(n + 2);
t += String.fromCharCode(
((r & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63),
);
n += 3;
}
}
return t;
},
};
export default Base64;
// Base64.decode(value);