前端自定义下载文件名

在这里插入图片描述

data数据格式如下

"data": [
        {
            "createBy": "system",
            "createTime": "2024-09-11 14:08:56",
            "updateBy": "",
            "updateTime": null,
            "beginTime": null,
            "endTime": null,
            "askParam": {},
            "formSpan": null,
            "id": 26,
            "sysCode": "system",
            "annexType": "1",
            "annexName": "系统操作手册",
            "iconUrl": "http://192.168.0.254:19000/secure/icon/2024/09/11/word.png",
            "annexUrl": "[{\"address\":\"annex/2024/09/11/ecd2e6b28b0c47468515b10ad2e1d7ff.docx\",\"name\":\"系统操作手册 .docx\",\"suffix\":\".docx\",\"url\":\"http://192.168.0.254:19000/secure/annex/2024/09/11/ecd2e6b28b0c47468515b10ad2e1d7ff.docx\",\"uid\":1726034934797,\"status\":\"success\"}]",
            "remark": "系统操作手册",
            "sysName": "系统"
        }
    ]
<el-button type="text" @click="download(scope.row)">本地下载</el-button>

download(data) {
    const url = JSON.parse(data.annexUrl);
    if (url.length > 0 && url[0].url) {
        this.downFile(url[0].url, data.annexName);
    }
},

    downFile(url, fileName) {
        const x = new XMLHttpRequest();
        x.open("GET", url, true);
        x.responseType = "blob";
        x.onload = function () {
            const url = window.URL.createObjectURL(x.response);
            const a = document.createElement("a");
            a.href = url;
            a.download = fileName;
            a.click();
        };
        x.send();
    },    
        
        
        // 或者 
        downFile1(url, fileName) {
            fetch(url)
                .then((response) => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.blob();
            })
                .then((blob) => {
                const downloadUrl = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = downloadUrl;
                a.download = fileName;
                a.click();
                a.remove();
                window.URL.revokeObjectURL(downloadUrl);
            })
                .catch((error) => {
                console.error('Download error:', error);
            });
        },  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值