一、直接创建一个不可见的 a 元素并模拟点击,如下所示:
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.style.display = 'none';
a.click();
document.body.removeChild(a);
低版本的Chrome浏览器(例如Chrome 83及更早的版本)可能不完全支持通过JavaScript生成的a标签并设置download属性来下载文件。这是因为这些浏览器对HTML5的支持尚不完全,特别是download属性在这些版本中可能没有得到充分实现。
以下是一些可能的原因和解决方法:
原因
不支持download属性:
低版本的Chrome可能不支持 a 标签的download属性,因此会导致文件在新窗口中打开而不是下载。
安全限制:
某些浏览器版本对动态创建的a 标签的安全性有严格限制,尤其是在跨域请求时可能无法正常下载文件。
二、为了确保在较旧版本的浏览器也能实现文件下载,可以使用一下方案。
方法 1:使用Blob对象和msSaveOrOpenBlob
对于支持Blob的浏览器,可以使用Blob对象并结合msSaveOrOpenBlob方法(适用于IE浏览器)。这不仅在现代浏览器中有效,也能在较旧的浏览器中更好地工作。代码如下:
<!DOCTYPE html>
<html>
<head>
<title>Download Example</title>
</head>
<body>
<button onclick="downloadFile('https://example.com/file.pdf', 'example.pdf')">Download PDF</button>
<script>
function downloadFile(url, filename) {
fetch(url)
.then(response => response.blob())
.then(blob => {
if (window.navigator.msSaveOrOpenBlob) {
// For IE
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
const a = document.createElement('a');
const objectUrl = URL.createObjectURL(blob);
a.href = objectUrl;
a.download = filename;
document.body.appendChild(a);
a.style.display = 'none';
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
}
})
.catch(error => console.error('Download error:', error));
}
</script>
</body>
</html>
方法 2:使用XMLHttpRequest和Blob对象
如果需要兼容更旧的浏览器,可以使用XMLHttpRequest来代替fetch
<!DOCTYPE html>
<html>
<head>
<title>Download Example</title>
</head>
<body>
<button onclick="downloadFile('https://example.com/file.pdf', 'example.pdf')">Download PDF</button>
<script>
function downloadFile(url, filename) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (xhr.status === 200) {
const blob = xhr.response;
if (window.navigator.msSaveOrOpenBlob) {
// For IE
window.navigator.msSaveOrOpenBlob(blob, filename);
} else {
const a = document.createElement('a');
const objectUrl = URL.createObjectURL(blob);
a.href = objectUrl;
a.download = filename;
document.body.appendChild(a);
a.style.display = 'none';
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(objectUrl);
}
}
};
xhr.send();
}
</script>
</body>
</html>
方法 3:使用隐藏的iframe
这种方法兼容性较好,适用于非常旧的浏览器:
<!DOCTYPE html>
<html>
<head>
<title>Download Example</title>
</head>
<body>
<button onclick="downloadFile('https://example.com/file.pdf')">Download PDF</button>
<script>
function downloadFile(url) {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = url;
document.body.appendChild(iframe);
// Optionally, remove iframe after download
setTimeout(() => {
document.body.removeChild(iframe);
}, 10000); // Adjust time as needed
}
</script>
</body>