js中使用iframe或者a标签根据服务器地址下载文件(json,txt等)如何直接下载文件而不是获取文件内容

问题遇到的现象和发生背景

使用a标签下载文件,浏览器会读取文件内容而不是直接下载下来

问题相关代码,请勿粘贴截图

const a= document.createElement('a'); // 创建a标签
a.setAttribute('download', '');// download属性
a.setAttribute('href', "http://192.168.50.44/file/001.json");
a.click();

运行结果及报错内容

img

我想要达到的结果

想要直接下载文件而不是在浏览器中读取出来

window.open()

download属性只在同域时候有效,当跨域请求时候该属性将会被忽略。
当前并非所以浏览器都支持该属性,需要浏览器考虑兼容性。
浏览器判断资源类型是根据返回头Content-Type的值,因此一方面我们在服务端可以设置返回头字段为文件流'Content-Type': 'application/octet-stream'

目前我采用的解决方案是通过文件地址把文件转成bolb流的形式进行下载,文件比较小,这种方式也满足目前的需求

function downloadBolbFile (url, fileName){
let xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.responseType = "blob";
xhr.onload = function () {
let blob = this.response;
let eleLink = document.createElement("a");
eleLink.download = fileName;
eleLink.style.display = "none";
eleLink.href = URL.createObjectURL(blob);
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
};
xhr.send();
};