文件链接下载,并重命名文件名

281 阅读1分钟

原因:

最近后端上传OBS文件,苦于无法打开链接后更改下载的文件名,便让我看看前端能不能处理一下。

// 假设后端返回了一个OBS上传后的文件链接
const downloadLink = 'https://demo.net/obs-yfxmgl/d/demo/test/2023/06/160-0519-XXXXXXXXXXXXXXXXXXXXX.log';

const downLoad = orginUrl => {  
const targetUrl = url => {  
//获取最后一个标识符的位置  
let slidIndex = url.lastIndexOf('/');  
let lineIndex = url.lastIndexOf('-');  
let extIndex = url.lastIndexOf('.');  
//得到目标url  
return `${url.substring(slidIndex + 1, lineIndex)}${url.substring(extIndex)}`;  
}  
fetch(`${orginUrl}?t=${new Date().getTime()}`)  
.then(response => response.blob())  
.then(blob => {  
let link = document.createElement('a');  
link.href = window.URL.createObjectURL(blob);  
// 重命名文件
link.download = targetUrl(downloadLink);  
link.click();  
});  
}
// 执行下载
downLoad(downloadLink);