javascript - 需要一个简单的 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 文件的建议文章/代码任何人都有我可以使用的示例或者上面的代码有什么问题?
解决方案
像这样的东西对你有用吗?
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) {}
}
推荐阅读
- flask-wtforms - Flask-WTF 使用 DateTimeLocal 设置最小值
- react-router - 如何在 NextJS 中呈现组件而不是页面?
- swift - 在集合上使用 KeyPath 的核心数据谓词
- javascript - 如何检测 WebView2 前后事件?
- python - 神经网络错误不会改变
- python - 数据框中日期更改的自动编号
- excel - 根据特定条件分配类别
- excel - 在参考单元格中查找特定数字并写入新单元格
- python - 字典迭代不会完全运行
- macos - 通过 iCloud 同步的 NSDocument 文件包装器似乎不支持同时在多台计算机上进行编辑