【vue】下载字符串拼接的文件链接并重命名文件
字符串拼接链接代码示例:
this.url = "http://127.0.0.1:8080/test/upload/20210128/2b35f9d7a64c3a6455a6e596c5c70fd7.xlsx";
this.filename = "导出文件";
this.html = '<button type="button" class="el-button el-button--primary el-button--small"><i class="el-icon-download"></i><a style="color:#fff;outline:none;" οnclick=download("'+this.url+'","'+this.filename+'.xlsx") href="#">下载</a></button>';
定义window函数
<script>
window.downloadFile = function (url,filename) {
getBlob(url, function(blob) {
saveAs(blob, filename);
})
};
function getBlob(url,cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = function() {
if (xhr.status === 200) {
cb(xhr.response);
}
};
xhr.send();
}
/**
* 保存
* @param {Blob} blob
* @param {String} filename 想要保存的文件名称
*/
function saveAs(blob, filename) {
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
var link = document.createElement('a');
var body = document.querySelector('body');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
// fix Firefox
link.style.display = 'none';
body.appendChild(link);
link.click();
body.removeChild(link);
window.URL.revokeObjectURL(link.href);
}
}
</script>
说明:
1.downloadFile函数定义到window中生效。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/92449.html