需求描述
- 需求:当点击按钮时,可以下载模板文件,下载地址如下
https://file2.clipworks.com/4c217acc09226795a7ebb8461ddf548f/20220726/469c1056-749d-4c47-819e-35f91c70e163
实现过程
实现代码
<div>
<a
class="el-button el-button--primary el-button--mini"
href='https://file2.clipworks.com/4c217acc09226795a7ebb8461ddf548f/20220726/469c1056-749d-4c47-819e-35f91c70e163'
download="视频教程模板"
>
模板下载
</a>
</div>
- a标签样式采用的是elementUI中按钮的样式
问题
按照如上代码,当点击按钮时并不会下载文件而是进行页面跳转(跳转到当前url)!
原因
若是href属性值为远程url,则具有同源策略,只有同源的url才会进行文件下载,若是不同源不会下载而是跳转!
解决
href属性值为远程url才会存在同源策略,我们可以创建一个本地url进行下载。
-
原生js
<div> <button id="btn">模板下载</button> </div> <script> const btn = document.getElementById('btn') btn.onclick = function(){ const xhr = new XMLHttpRequest() xhr.open('get','https://file2.clipworks.com/4c217acc09226795a7ebb8461ddf548f/20220726/469c1056-749d-4c47-819e-35f91c70e163') xhr.responseType='blob' xhr.send() xhr.onload = function(){ // 1. 根据远程URL创建本地url const localUrl = URL.createObjectURL(xhr.response) // 2. 创建a标签,并点击下载文件 const linka = document.createElement('a') linka.setAttribute('href', localUrl) linka.setAttribute('download', '视频教程模板') linka.click() // 3.清除工作 URL.revokeObjectURL(localUrl) // 清除创建的本地url } } </script>
-
vue中
<template> <div style="margin-top:20px"> <a class="el-button el-button--primary el-button--mini" :href='url' download="视频教程模板" id='downloadBtn' target='_blank'>模板下载</a> </div> </template> <script> export default { data(){ return{ url:undefined } }, created(){ this.getLocalUrl() }, methods:{ getLocalUrl(){ // 根据远程url创建本地url const url = 'https://file2.clipworks.com/4c217acc09226795a7ebb8461ddf548f/20220726/469c1056-749d-4c47-819e-35f91c70e163' const xhr = new XMLHttpRequest() xhr.open('GET', url) xhr.responseType = "blob" xhr.onload = ()=>{ this.url = URL.createObjectURL(xhr.response) } xhr.onerror = e =>{ console.log('err', e) } xhr.send() } } } </script>
知识点
- 文件下载 -> a标签/使用3-文件下载
- 原生http请求 -> XMLHttpRequest构造函数
- 创建本地url -> URL构造函数的createObjectURL函数
- http响应头的content-disposition属性 ->http响应头的content-disposition属性