export default (data, name='sprite', suffix='xxx') => {
const contentType = {
// 基本类型
'txt': 'text/plain',
'png': 'image/png',
'jpeg': 'image/jpeg',
'jpg': 'image/jpeg',
// 自定义类型
'xxx': 'text/plain',
};
if (contentType[suffix]) {
const fileName = name + '.' + suffix;
const file = new Blob([JSON.stringify(data)], { type: contentType[suffix] });
if (window.navigator.msSaveOrOpenBlob) { // IE10+
window.navigator.msSaveOrOpenBlob(file, fileName);
} else {
// Others
const a = document.createElement('a');
const url = URL.createObjectURL(file);
a.href = url;
a.download = fileName;
document.body.appendChild(a);
a.click();
// 下一个事件循环,删除掉 a 元素
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
console.log('File has been saved:', fileName);
} else {
console.log('File not saved. Suffix not exist:', suffix);
}
};
网友评论