刚开始调用方法downloadFile('./aoFile.ovkml', 'ovkml模板'),filname没有写文件格式,导致下载为txt文件,修改后downloadFile('./aoFile.ovkml', 'ovkml模板.ovkml');ovkml文件下载成功,以下是完整代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Download OVKML File</title>
</head>
<body>
<button id="downloadBtn">下载 OVKML File</button><script>async function downloadFile(url, filename) {try {const response = await fetch(url);if (!response.ok) {throw new Error(`Network response was not ok: ${response.statusText}`);}const blob = await response.blob();const urlObject = URL.createObjectURL(blob);const a = document.createElement('a');a.style.display = 'none';a.href = urlObject;a.download = filename;document.body.appendChild(a);a.click();setTimeout(() => {document.body.removeChild(a);window.URL.revokeObjectURL(urlObject);}, 0);} catch (error) {console.error('There was a problem with the fetch operation:', error);}}document.getElementById('downloadBtn').addEventListener('click', function() {downloadFile('./aoFile.ovkml', 'ovkml模板.ovkml');});
</script>
</body>
</html>