首页 > 解决方案 > 需要一个简单的 javascript 示例来下载 zip 文件

问题描述

我正在尝试在我的网络服务器上添加代码以从我们的远程网站下载文件。(我只是以微软下载文件为例)

<p>
<script type = "text/javascript">

document.write('<iframe src="https://download.microsoft.com/download/E/9/8/E9849D6A-020E-47E4-9FD0-A023E99B54EB/requestRouter_amd64.msi" size="0" width="0" height="0" style="display: none"></iframe>');

document.write('<table><tr>');
document.write('<td><span style="font-weight: normal; font-size: 20pt; color: #666666;">Thank you for downloading</span></td><br />');
document.write('</tr></table>');

</script>  
</p>

此 iframe 不起作用。我也试过:

<p>
<script type = "text/javascript">

function download(file, text) { 
var element = document.createElement('a'); 
element.setAttribute('href', 'data:text/plain;base64, ' + encodeURIComponent(text)); 
element.setAttribute('download', file); 
document.body.appendChild(element); 
element.click(); 
document.body.removeChild(element); 
} 

document.write('<table><tr>');
document.write('<td><span style="font-weight: normal; font-size: 20pt; color: #666666;">Thank you for downloading</span></td><br />');
document.write('</tr></table>');

var text = "any text"; 
var filename = "https://download.microsoft.com/download/E/9/8/E9849D6A-020E-47E4-9FD0-A023E99B54EB/requestRouter_amd64.msi"; 
download(filename, text); 

</script>  
</p>

但这也不起作用。我已经尝试过客户端下载服务器生成的 zip 文件的建议文章/代码任何人都有我可以使用的示例或者上面的代码有什么问题?

标签: javascriptdownload

解决方案


像这样的东西对你有用吗?

async function downloadFile(fileData, fileDataContentType) {
try {
    
    const blob = new Blob([fileData], { type: fileDataContentType });
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = 'randomFileName';
    link.click();
} catch (error) {}

}


推荐阅读