前端文件下载的打开方式

1.a标签

<a href="http://ww.baidu.con" download="baidu.html">下载</a>

点击下载,跳到的是百度的首页,并没有真的下载文件。因为a标签只能下载同源文件,如果是跨域文件,包括图片、音视频等媒体文件,都是预览,无法下载。
可以通过js来实现

const a = document.createElement('a')
a.href= 'http://www.baidu.com'
a.download = 'baidu.html'
a.click()

效果和上面的一样,都是跳转到=百度的首页。重点是a标签的download属性,这个属性是html5新增的。它的作用是指定文件的下载名,如果不指定,那么下载的文件名就会根据请求内容的Content-Disposition来确定,如果没有Content-Disposition,那么就会使用请求的URL的最后一部分作为文件名。

2.window.open

与上面a标签的效果一样

window.open('http://www.baidu.com','_blank','download=baidu.html')

_blank是在新页面打开,a标签的doenload在这里也是可以使用的。
这种方式不能下载 .html.htm.xml.xhtml等文件,因为这些文件会被当成html来处理,所以会直接在当前页面打开。同样也不能下载跨域文件

3.location.href

这种方式和widow.ope(url)```是一样的,这种方式拥有```window.open的所有缺陷,不推荐使用

location.href = 'http://www.baidu.com'

4.location.其他属性

location.assign('http://www.baidu.com')
location.replace('http://www.baidu.com')
location.reload('http://www.baidu.com')

这些属性都可以实现文件的下载,同location.href一样,这些方式的缺点都一样,同时还有属于每个属性自身的特性。location.reload有点特殊,它的作用是重新加载当前页面。

5.XMLHttpRequest

这种方式就是ajax下载,包括axios、fetch等都是相同的

const xhr = new XMLHttpRequest()
xhr.open('get','http://www.baidu.com')
xhr.send()
xhr.onload = function(){
    
    
const blob = newBlob([xhr.response],{
    
    type:'text/html'})
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.download = 'baidu.html'
a.click(0
}

主要逻辑是请求成功后,拿到响应体的response,这个reponse就是要下载的内容,然后把它转成bolb对象,通过URL.createObjectURL来创建一个url,然后通过a标签的doenload属性来实现文件下载。

猜你喜欢

转载自blog.csdn.net/weixin_54722719/article/details/128181575