[Front-end file download] The two most common ways for Js Vue to download files

Table of contents

1. Download the first file stream format

 2. Download through static url

At present, the most commonly used methods for downloading files at the front end are as follows:

(1) Download by receiving the file stream format (Blob data) returned by the backend

(2) Download by receiving the file url address given by the backend

1. Download the first file stream format

In this case, our front end usually initiates a download request to the back end, and the back end will return the code in the file stream format (Blob data) after receiving it, and then we pass in the Blob data through the new Blob() method, and then pass the obtained data to Enter window.URL.createObjectURL() and finally get the url. We create an a tag, then assign the url to the href of the a tag, then use the link.setAttribute() method to set the file name, add the set link data to the a tag node link.click(); trigger the click event, and finally Remove the link on the a tag

/**
 *
 * @param {*} data 文件数据
 * @param {*} fileName 文件名称
 * @param {*} fileFormat 文件格式
 * @returns
 */
export default function exportDownload(data, fileName = '导出文件', fileFormat = 'xlsx') {
  // data为Blob数据
  if (!data) {
    return;
  }
  // 执行下载
  const url = window.URL.createObjectURL(new Blob([data]));
  console.log(url);
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', `${fileName}.${fileFormat}`);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

 2. Download through static url

In this way, I also use the a tag to achieve it. First, create an a tag const elt = document.createElement('a'); Then set the href attribute on the a tag to pass in the url, and the download property to pass in the file Name, add the set link data to the a label node link.click(); trigger the click event, and finally remove the link on the a label

/**
 *
 * @param {*} url 文件路径
 * @param {*} name 文件路径
 * @returns
 */
export default function downloadFile(url, name) {
  const elt = document.createElement('a');
  elt.setAttribute('href', fileDownload(url));
  elt.setAttribute('download', name);
  elt.style.display = 'none';
  document.body.appendChild(elt);
  elt.click();
  document.body.removeChild(elt);
}

 

 

Guess you like

Origin blog.csdn.net/weixin_49014702/article/details/127918426