a标签下载文件并自定义文件名

  一、href的属性地址必须是和你前端同源情况下

<a href="URL" download="文件名"> //download属性也可以设置一个值来规定下载文件的名称。所允许的值没有限制,浏览器将自动检测正确的文件扩展名并添加到文件。

注意:只有 Firefox 和 Chrome 支持 download 属性,如果涉及跨域情况下,download将不会起作用。

二、href属性地址与当前前端地址不同源的情况。

// HTML代码
<a href="javascript:void(0);" @click="downLoad(scope.row)">
        {{ scope.row.originalFileName }}
    </a>
 
    // 下载方法
 
   downLoad (row) {
      const x = new window.XMLHttpRequest();
      x.open('GET', row.originalFileUrl, true);
      x.responseType = 'blob';
      x.onload = () => {
        const url = window.URL.createObjectURL(x.response);
        const a = document.createElement('a');
        a.href = url;
        a.target = '_blank'
        a.download = row.originalFileName;
        a.style.display = 'none'
        document.body.append(a)
        a.click();
      };
      x.send();
    },
 


posted @ 2023-09-05 09:33  linzhanfeng  阅读(3370)  评论(0编辑  收藏  举报