关于javascript:下载文件并重命名文件名称

话不多说,间接上菜,请各位大佬提出不同意见

/**
 * @filename <string> 自定义的文件名
 * @url <string> 下载地址
 */
export function renameDownloadFile(filename,url){
  // 获取文件
  getBlob(url).then(blob => {
    // 保留文件
    saveAs(blob, filename);
  })
}
// 重命名下载
export function getBlob(url) {
  // 创立Promise对象
  return new Promise(resolve => {
    // 创立XMLHttpRequest对象
    const xhr = new XMLHttpRequest();
    // 设置申请形式
    xhr.open('GET', url, true);
    // 设置响应类型
    xhr.responseType = 'blob';
    // 当申请实现时,触发onload事件
    xhr.onload = () => {
      // 如果响应状态码为200,则解析响应
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };
    // 发送申请
    xhr.send();
  });
}
export function saveAs(blob, filename) {
  // 如果反对msSaveOrOpenBlob办法,则应用msSaveBlob办法保留文件
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename);
  } else {
    // 创立a标签
    const link = document.createElement('a');
    // 获取body元素
    const body = document.querySelector('body');
    // 设置a标签的href属性
    link.href = window.URL.createObjectURL(blob);
    // 设置a标签的download属性
    link.download = filename;
    // 当a标签被点击时,触发onclick事件
    // fix Firefox
    link.style.display = 'none';
    body.appendChild(link);

    // 点击a标签,触发onclick事件
    link.click();
    // 销毁a标签
    body.removeChild(link);
    // 开释a标签的href属性
    window.URL.revokeObjectURL(link.href);
  }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理