vue下载PDF文件到本地

方法1.

downloadPDF(fileName) {
  // 要下载的文件路径
  var fileUrl = './file/' + fileName;
  // 创建一个隐藏的<a>元素,用于下载文件
  var a = document.createElement('a');
  a.href = fileUrl;
  a.download = fileName; // 可以自定义下载文件的名称
  a.style.display = 'none';
  // 将<a>元素添加到页面上
  document.body.appendChild(a);
  // 触发点击事件,开始下载
  a.click();
  // 下载完成后,移除<a>元素
  document.body.removeChild(a);
}

方法2.

downloadPDF(fileName) {
  const fileUrl = './file/' + 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);
  });
}

 

posted @ 2023-09-28 09:34  借你耳朵说爱你  阅读(1944)  评论(0编辑  收藏  举报