一、生成 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 = '一段文本.'
const blob = new Blob([stringData], {
type: "text/plain;charset=utf-8"
})
const objectURL = URL.createObjectURL(blob)
const aTag = document.createElement('a')
aTag.href = objectURL
aTag.download = "文本文件.txt"
aTag.click()
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)
const blob = new Blob([stringData], {
type: 'application/json'
})
const objectURL = URL.createObjectURL(blob)
const aTag = document.createElement('a')
aTag.href = objectURL
aTag.download = "json文件.json"
aTag.click()
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## 二级标题'
const blob = new Blob([stringData], {
type: 'text/markdown'
})
const objectURL = URL.createObjectURL(blob)
const aTag = document.createElement('a')
aTag.href = objectURL
aTag.download = "markdown文件.md"
aTag.click()
URL.revokeObjectURL(objectURL)
}
}
</script>
</body>
</html>