EG:
/**
* 文件下载
*
* @param {string} content - 内容
* @param {string} fileType - 文件类型
*/
const downoadContentFile = (content, fileType) => {
// dom中创建a标签
const eleLink = document.createElement('a');
// blob是js内置对象,用来处理二进制文件流
const blob = new Blob([content]);
// 给创建的a标签添加download属性,此属性是让我们的浏览器下载URL而不是跳转到URL所指向的内容
eleLink.download = `${Date.parse(new Date())}.${fileType}`;
// 给创建的a标签添加href属性并赋值
eleLink.href = URL.createObjectURL(blob);
// 自动点击创建的标签
eleLink.click();
// 不再使用时需释放createObjectURL创建的对象
URL.revokeObjectURL(blob);
}
export { downoadContentFile }
使用
import { downoadContentFile } from "@utils";
downoadContentFile ("测试数据", "txt")