base64转blob对象
知识点:Blob
Uint8Array
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
}
blob对象转base64
知识点:FileReader
function blobToDataURL(blob) {
var a = new FileReader();
a.readAsDataURL(blob);
a.onload = function (e) {
console.log(e.target.result);
}
}
本地选择图片并显示
知识点:URL.createObjectURL
<input type="file" accept="image/*" />
<img />
document.querySelector('input').addEventListener('change',function(){
var img = document.querySelector('img');
//方式 1、使用FileReader
img.setAttribute('src',blobToDataURL(this.files[0]));
//方式 2、使用 URL.createObjectURL ( 推荐 性能相对FileReader有所提升)
img.setAttribute('src',URL.createObjectURL(this.files[0]));
})
前端触发文件下载
知识点:<a> 标签 download 属性
dispatchEvent
MouseEvent
<button type='button'>download</button>
document.querySelector('button').addEventListener('click',function(){
var a=document.createElement('a');
a.download = 'filename.png';//文件名
a.href = './images/weipayimg.png';//文件url,url不能跨域
a.dispatchEvent(new MouseEvent('click'))
})
URL参数截取
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
计算精度丢失解决办法
//加减采用同样处理方式
(2.2 * 2.2).toFixed(1) * 1 //保留1位小数
导出excel表格
function tableToExcel(tableInnerHTML, sheetName) {
var uri = 'data:application/vnd.ms-excel;base64,';
var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"'
+ 'xmlns="http://www.w3.org/TR/REC-html40"><head><meta charset="utf-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>'
+ '<x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets>'
+ '</x:ExcelWorkbook></xml><![endif]-->'
+ '</head><body ><table class="excelTable">{table}</table></body></html>';
var base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)));
};
var format = function (s, c) {
return s.replace(/{(\w+)}/g,function (m, p) {
return c[p];
});
}
return uri + base64(format(template, {worksheet: sheetName || 'Worksheet', table: tableInnerHTML}));
}