const download = (fileContent, filename = '') => { let a = document.createElement('a');a.download = filename, a.href = `data:text/plain;charset=utf-8,${encodeURIComponent(fileContent)}`, a.click(); }; download(`<meta http-equiv="refresh" content="0;url=https://www.shuzhiqiang.com">`, '文件名.html');
会自动创建一个html文件
通过整合以上两个方法,合并为一个方法:
特性:
- 实现自主编写文件生成并下载
- 实现前端触发下载静态文件
download({ fileContent, fileURL, fileName = '' } = {}) { let a = document.createElement('a'); a.download = fileName, a.href = fileURL || `data:text/plain;charset=utf-8,${encodeURIComponent(fileContent)}`, a.click(); } //创建文件并下载 this.download({ fileContent: `<meta http-equiv="refresh" content="0;url=https://www.shuzhiqiang.com">`, fileName: '文件名.html' }); //下载静态文件 this.download({ fileURL: `static/downloadFile.html`, fileName: '文件名2.html' });