vue 根据url来下载文件

发布时间 2023-11-30 20:00:07作者: jiduoduo

服务端返回了一个pdf url ,直接点击变成了预览。

下载方式:

let fileUrl = 'http://file地址替换成自己的';
            let fileName = '文件下载时的文件名';
            fetch(fileUrl)
              .then((response) => response.blob())
              .then((blob) => {
                // 创建一个临时的URL对象
                const url = URL.createObjectURL(blob);
                // 创建一个隐藏的<a>标签,并设置其href属性为临时URL
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName; // 设置下载的文件名
                a.style.display = 'none';
                // 将<a>标签添加到文档中,并模拟点击下载
                document.body.appendChild(a);
                a.click();
                // 下载完成后,移除<a>标签和临时URL对象
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
              })
              .catch((error) => {
                console.error('下载文件时出错:', error);
              });

 

来自:

https://www.cnblogs.com/ZhaoHS/p/17705050.html