[Common codes] Use a tag in vue to download files pdf, docx, doc, xls, etc., and assign file names

Problem Description

There is a file path, the project domain name + file path is opened, and the file can be downloaded directly in the new window of the browser.
Opening with window.open will read the pdf instead of downloading the pdf file

这种也不是向后台发送请求获取blob文件流

So use the a tag to download files


solution:

Tip: Fill in the specific solution to the problem here:

// 使用a标签下载
export function fileDown(blobUrl, filename) {
    
    
  const a = document.createElement("a");
  if (!a.click) {
    
    
    throw new Error('DownloadManager: "a.click()" is not supported.');
  }
  a.href = blobUrl;
  a.target = "_parent";
  if ("download" in a) {
    
    
    a.download = filename;
  }
  (document.body || document.documentElement).append(a);
  a.click();
  a.remove();
}


Specific use:

  1. Encapsulate a tool js in utils, called fileDown.js
  2. Introduce this js in the vue project ==>
import {
    
     fileDown } from "@/utils/fileDown.js"
  1. The method of use is
fileDown(process.env.VUE_APP_BASE_API + item.url, item.name)

process.env.VUE_APP_BASE_API is your project address, getting the domain name is the same effect,

192.168.1.6:8080 + /upload/2023/4/14/filename_************.pdf
restore that's it
insert image description here

おすすめ

転載: blog.csdn.net/qq_51055690/article/details/130147940