Browser download file method

Use fetchthe API to get the file data and create a Blob object. Then, trigger the download by creating a temporary <a>tag and using URL.createObjectURL()to generate the temporary URL. Doing so will automatically download the file without opening it in the browser after the user clicks download. After the download is complete, remove the temporary <a>tags to ensure that no extra elements are left in the DOM. 

    async downloadFile() {
      const fileUrl = ''; //设置要下载的文件链接

      try {
        // 使用 fetch API 下载文件
        const response = await fetch(fileUrl);
        const blob = await response.blob();

        // 创建一个 <a> 标签
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);

        // 设置下载的文件名,这里假设文件名为 示例文件.pdf
        link.download = '示例文件.pdf';

        // 将 <a> 标签加入 DOM,并触发点击下载
        document.body.appendChild(link);
        link.click();

        // 下载完成后移除 <a> 标签
        document.body.removeChild(link);
      } catch (error) {
        console.error('下载文件出错:', error);
        // 处理下载出错的情况
      }
    },

Guess you like

Origin blog.csdn.net/qq_53478650/article/details/132146288