JS 解决txt文件直接打开而不是下载

PS:后台传过来的路径不可以直接下载txt文件:先创建a标签然后把路径填入,download属性一定要填上下载的文件的名称,可以解决txt文件直接打开而不是下载

var url = "../../../Temp/14049234c3ef498583f9ff213b5b5529/D05B567C0602414D8CCFFDCA677DE060.txt";
//创建a标签
var a = document.createElement('a');
a.setAttribute('href', url);
a.setAttribute('download', url.split('/').pop()); //分割路径,取出最后一个元素
a.setAttribute('target', '_blank');
a.setAttribute('id', 'DownloadFile');
// 防止反复添加
if(document.getElementById('DownloadFile')) {
    document.body.removeChild(document.getElementById('DownloadFile'));
}
document.body.appendChild(a);
a.click();
原文地址:https://www.cnblogs.com/combat/p/11102995.html