赞
踩
iframe、a标签下载文件都是调用浏览器默认下载行为
iframe闭合标签,会创建包含另个文档的内联框架,通过iframe实现文件(附件)的下载,隐藏iframe,当点击事件触发的时候,动态设置src就能实现文件下载功能
元素(或称锚元素)可以通过它的 href 属性创建通向其他网页、文件、同一页面内的位置、电子邮件地址或任何其他 URL 的超链接。
<template>
<div id="app" class="container">
<!-- <img alt="Vue logo" src="./assets/logo.png" style="width: 40px; margin-left: 145px; margin-top: 40px; margin-bottom: 7px;"> -->
<!-- <UploadPhoto></UploadPhoto> -->
<div style="margin: 50px 0px; display: flex;">
<div style="margin-right: 10px; color: grey;">
<div>通过iframe、a标签实现文件下载功能</div>
<div>点击按钮下载 'QQ9.7.1.28934.exe' 文件</div>
</div>
<div>
<el-button type="primary" @click="loadFile">点击下载</el-button>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'App',
components: {
// Demo
},
data() {
},
created() {
//
},
methods: {
// iframe标签
loadFile() {
console.log("asda")
let url = 'https://dldir1.qq.com/qqfile/qq/PCQQ9.7.1/QQ9.7.1.28934.exe';
const iframe = document.createElement('iframe'); // 创建一个HTML 元素
iframe.style.display = 'none'; // 隐藏iframe 防止影响页面
iframe.style.height = 0; // 高度设置0 防止影响页面
iframe.src = url;// 下载链接
document.body.appendChild(iframe); // 这一行必须,iframe挂在到dom树上才会发请求 // 5分钟之后删除
setTimeout(() => { iframe.remove(); }, 5 * 60 * 1000);
console.log("111asda")
},
// a标签
loadFile2() {
const a = document.createElement('a'); // 创建一个HTML 元素
let url = 'https://dldir1.qq.com/qqfile/qq/PCQQ9.7.1/QQ9.7.1.28934.exe';
a.setAttribute('download', ''); //download属性
a.setAttribute('href', url); // href链接
a.click(); // 自执行点击事件
}
}
}
</script>
<style>
.el-input {
width: 200px !important;
}
</style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。