Appearance
JS工具函数
JS实现图片Base64格式转化为png
JS实现图片Base64格式转化为Png/Jpg,并保存至本地
const Base64ConvertToImage = (saveName, b64Info, contType) => { /** base64文件流并保存到本地png/jpg*/
const b64toBlob = (b64Data, contentType = "image/png", sliceSize = 512) => {
//-- parse base64 string
const byteCharacters = window.atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
//-- https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
//-- https://developer.mozilla.org/zh-CN/docs/Web/API/Blob
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}
const blob = b64toBlob(b64Info, contType);
//-- https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
//-- URL.createObjectURL() 静态方法会创建一个 DOMString
const blobUrl = URL.createObjectURL(blob);
const aEle = document.createElement("a");
const evt = document.createEvent("HTMLEvents");
//-- 初始化,事件类型,是否冒泡,是否阻止浏览器的默认行为
evt.initEvent("click", true, true);
aEle.download = saveName;
aEle.href = blobUrl;
aEle.click();
}
export default Base64ConvertToImage;
参考资料:
https://www.zhangxinxu.com/wordpress/2018/08/js-base64-atob-btoa-encode-decode/
https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript
JS在线预览Excel
主要通过js-xlsx读取本地或者服务端的Excel的内容,实际业务中可以根据需求进行不同的处理操作。
具体的实现过程可参照js-xlsx官网体统的demo,也可以参照如下简易版GridDemo进行实际的业务扩展。
JS正则时间格式化
- 数字字符串格式转datetime格式
let timeStr = '20190526153600'
timeStr = timeStr.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, '$1-$2-$3 $4:$5:%6')
console.log(timeStr) //- - 2019-05-25 15:36:00
- 含有汉字的时间格式提取为【yyyy-mm-dd】
let dtDate = '2019年05月26日 15:40:23'
dtDate = dtDate.replace(/(\d{4}).(\d{1,2}).(\d{1,2}).+/mg, '$1-$2-$3')
console.log(dtDate) //- - 2019-05-26
- 含有汉字的时间格式提取为【yyyymmdd】
let dtData = '2019年05月26日 15:40:23'
dtDate = dtDate.replace(/[^[0-9]]/mg,'').match(/.\d{8}/)
console.log(dtDate) //- - 20190526