Skip to content

js下载字符串为文件

js
var aLink = document.createElement('a')
var fileName = '文件名'
var obj = { hello: 'world' }
var blob = new Blob([JSON.stringify(obj, null, 2)], {
    type: 'application/json'
})
aLink.href = URL.createObjectURL(blob)
aLink.setAttribute('download', fileName) // 设置下载文件名称
document.body.appendChild(aLink)
aLink.click()
document.body.removeChild(aLink)
URL.revokeObjectURL(aLink.href)