通过隐藏iframe实现文件下载的js方法介绍

1,779 阅读1分钟

代码示例

<script>
function download(){
  //下载文件的地址
var url="http://music.baidu.com/data/music/file?link=http://zhangmenshiting.baidu.com/data2/music/13618994/13618995183600128.mp3?xcode=48d4a720fcd9a974586066d0145f7207";
document.getElementById("ifile").src=url;
}
</script>
<body>
<a href="#" onclick="download()">download</a>
<iframe id="ifile" style="display:none"></iframe>
</body>

相关知识点

1.什么是iframe?

iframe闭合标签,会创建包含另个文档的内联框架,针对不支持iframe的浏览器,可以将提示文字放在iframe之间。

2.iframe的作用

  • 通过iframe实现文件(附件)的下载

通过隐藏iframe,当点击事件触发的时候,动态设置src就能实现文件下载功能。

<a href="#"  onclick="download()">download</a>
<iframe id="ifile" style="display:none"></iframe>

function download(){
  var dom=document.getElementById('ifile');
  dom.src="http:xxxx.com";
}
  • 通过iframe实现图片上传或者说表单的提交

这样,点击事件会触发upload(),并且触发表单提交,并且提交的同时不会刷新页面

<iframe id="upload_target" name="upload_target" src="upload.php" style="width:0;heigth:0;overflow:hidden;border:0;position: absolute; left:-500px;"></iframe>

<form enctype="multipart/form-data" action="upload.php" method="post" target="upload_target">  
  <input type="file" name="userfile" class="file" value="" />  
  <input type="submit" name="uploadimg" value="上传" onClick="upload()"/>  
</form> 

3.iframe有什么缺点

  • iframe会阻塞主页的onload事件
  • 搜索页面无法解读这种页面(不利于SEO)
  • iframe和主页面会共享连接池,而浏览器对于相同区域有限制,所以会影响性能。