该方法可以解决,需要下载一些需要授权的文件。如果是不需要授权的文件可以直接用官网封装的方法进行下载。
<script>
/**
*
* @param {*} url 文件请求路径 例如:https://www.ruoyi.vip/a.png
* @param {*} name 下载的文件名 例如: a.png
* @param {*} opts
*/
import { getToken } from '@/utils/auth'
function download (url, name, opts) {
var xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'blob'
xhr.setRequestHeader("Authorization",'Bearer ' + getToken() )
xhr.onload = function () {
saveAs(xhr.response, name, opts)
}
xhr.onerror = function () {
console.error('could not download file')
}
xhr.send()
}
//调用方法示例
this.download("https://www.ruoyi.vip/a.png","a.png");
</script>
// 自定义文本保存
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
this.download.saveAs(blob, "hello world.txt");
// 自定义文件保存
var file = new File(["Hello, world!"], "hello world.txt", {type: "text/plain;charset=utf-8"});
this.download.saveAs(file);
// 自定义data数据保存
const blob = new Blob([data], { type: 'text/plain;charset=utf-8' })
this.download.saveAs(blob, name)
// 根据地址保存文件
this.download.saveAs("https://ruoyi.vip/images/logo.png", "logo.jpg");
const name = "be756b96-c8b5-46c4-ab67-02e988973090.xlsx";
const isDelete = true;
// 默认下载方法
this.download.name(name);
// 下载完成后是否删除文件
this.download.name(name, isDelete);
const resource = "/profile/upload/2023/11/17/be756b96-c8b5-46c4-ab67-02e988973090.png";
// 默认方法
this.$download.resource(resource);
const url = "/tool/gen/batchGenCode?tables=" + tableNames;
const name = "ruoyi";
// 默认方法
this.$download.zip(url, name);
powered by kaifamiao