点击采用a标签下载 点击采用流下载
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btn").on('click', function () {
downloadTxt("hello.txt","This is the content of my file");
})
$("#btn2").on('click', function () {
downloadByBlob("zqf.txt","What's up , hello world");
})
})
//通过a标签指定文本格式和编码直接下载
function downloadTxt(fileName, content) {
let a = document.createElement('a');
a.href = 'data:text/plain;charset=utf-8,' + content
a.download = fileName
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
//通过FileReader转化为base64字符串下载
function downloadByBlob (fileName, content) {
let blob = new Blob([content], {
type: "text/plain;charset=utf-8"
});
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function(e) {
let a = document.createElement('a');
a.download = fileName;
a.href = e.target.result;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
}
</script>
</body>