一、生成 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>
转载标题:[JS] 将字符串保存为本地文件(.txt、.json、.md...) 转载地址:https://www.123yun.com/article/1049.html
http代理服务器安装 在线服务器proxy 开发代理服务器 代理服务器要钱吗