文章目录
-
- 一、生成 TXT 文件
- 二、生成 JSON 文件
- 三、生成 Markdown 文件
一、生成 TXT 文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>保存文件</title>
</head>
<body>
<button type="button" id="button"> 保存文件</button>
<script type="text/javascript">
window.onload = function(event) {
main()
}
function main() {
// 获取按钮
const button = document.getElementById('button')
// 给按钮添加点击事件
button.onclick = () => {
// 要保存的字符串
const stringData = '一段文本.'
// dada 表示要转换的字符串数据,type 表示要转换的数据格式
const blob = new Blob([stringData], {
type: "text/plain;charset=utf-8"
})
// 根据 blob生成 url链接
const objectURL = URL.createObjectURL(blob)
// 创建一个 a 标签Tag
const aTag = document.createElement('a')
// 设置文件的下载地址
aTag.href = objectURL
// 设置保存后的文件名称
aTag.download = "文本文件.txt"
// 给 a 标签添加点击事件
aTag.click()
// 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
// 当你结束使用某个 URL 对象之后,应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
URL.revokeObjectURL(objectURL)
}
}
</script>
</body>
</html>
二、生成 JSON 文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>保存文件</title>
</head>
<body>
<button type="button" id="button"> 保存文件</button>
<script type="text/javascript">
window.onload = function(event) {
main()
}
function main() {
// 获取按钮
const button = document.getElementById('button')
// 给按钮添加点击事件
button.onclick = () => {
// 要保存的字符串, 需要先将数据转成字符串
const stringData = JSON.stringify([{name: "张三",age: 18}], null, 2)
// dada 表示要转换的字符串数据,type 表示要转换的数据格式
const blob = new Blob([stringData], {
type: 'application/json'
})
// 根据 blob生成 url链接
const objectURL = URL.createObjectURL(blob)
// 创建一个 a 标签Tag
const aTag = document.createElement('a')
// 设置文件的下载地址
aTag.href = objectURL
// 设置保存后的文件名称
aTag.download = "json文件.json"
// 给 a 标签添加点击事件
aTag.click()
// 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
// 当你结束使用某个 URL 对象之后,应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
URL.revokeObjectURL(objectURL)
}
}
</script>
</body>
</html>
三、生成 Markdown 文件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>保存文件</title>
</head>
<body>
<button type="button" id="button"> 保存文件</button>
<script type="text/javascript">
window.onload = function(event) {
main()
}
function main() {
// 获取按钮
const button = document.getElementById('button')
// 给按钮添加点击事件
button.onclick = () => {
// 要保存的字符串
const stringData = '# 一级标题\n## 二级标题'
// dada 表示要转换的字符串数据,type 表示要转换的数据格式
const blob = new Blob([stringData], {
type: 'text/markdown'
})
// 根据 blob生成 url链接
const objectURL = URL.createObjectURL(blob)
// 创建一个 a 标签Tag
const aTag = document.createElement('a')
// 设置文件的下载地址
aTag.href = objectURL
// 设置保存后的文件名称
aTag.download = "markdown文件.md"
// 给 a 标签添加点击事件
aTag.click()
// 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
// 当你结束使用某个 URL 对象之后,应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
URL.revokeObjectURL(objectURL)
}
}
</script>
</body>
</html>
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论(0)