Frontend: Datei herunterladen (mehrere Methoden)

1. Einleitung

Das Frontend muss häufig Dateien herunterladen. Hier sind einige häufig verwendete Methoden, um die Anzeige in Zukunft zu vereinfachen.

Zweitens ein Label-Download

<a href="https://abc.png" download="abc.png" target="view_window">Version</a>

Drei, window.open herunterladen

downloadTemple() {
      window.open(`url`);
    },

4. location.href

location.href = 'https://a.png';

5. Speichern unter

saveAs('https://abc.png')

Sechs, LoadFileSimply

6.1、loadFileSimply

// loadFileOps.js
import axiosOps from 'axios';
import cookie from 'js-cookie';
import { hasIn } from 'lodash';
import Vue from 'vue';

export const $loadFileSimply = param => {
  let token = cookie.get('token');
  let tenantId = cookie.get('tenantId');
  param.url += param.url.indexOf('?') > -1 ? '&' : '?';
  param.url += `tenantId=${tenantId}&_=${new Date().getTime()}`;
  return new Promise((resolve, reject) => {
    axiosOps({
      url: param.url,
      method: param.method,
      data: param.data,
      params: param.params,
      responseType: 'arraybuffer', // 请求成功时,后端返回文件流,正常导出文件;
      headers: {
        Authorization: `Bearer ${token}`,
        tenantId: tenantId
      },
      timeout: param.timeout ? param.timeout : 5000
    })
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        Vue.$notify.error({
          title: '错误提示',
          message: '下载文件失败'
        });
        reject(err)
      });
  });
};

6.2、DateiHerunterladen

// 内容转化为文件下载
export const fileDownload = (file, fileName = '下载文件', options) => {
  // 创建隐藏的可下载链接
  let eleLink = document.createElement('a')
  eleLink.download = fileName
  eleLink.style.display = 'none'
  // 字符内容转变成blob地址
  let blob = options ? new Blob([file], options) : new Blob([file])
  eleLink.href = URL.createObjectURL(blob)
  // 触发点击
  document.body.appendChild(eleLink)
  eleLink.click()
  // 然后移除
  document.body.removeChild(eleLink)
}

6.3. Verwendung

import { $loadFileSimply } from '@const/loadFileOps';
import { fileDownload } from '@const/utils.js';

downloadTemple() {
      $loadFileSimply({
        url: downloadUrl,
        method: 'post',
        params: { tempCode: 'SAAS_PUR_ORDER_TEMP' },
      })
        .then((res) => {
          fileDownload(res, '文件名称.xlsx'); // 下载并修改文件名
        })
        .catch(() => {
          this.$message.error('下载模板失败!');
        });
    },

Sieben, URL-Download

// 地址下载,fileName暂无作用
export const urlDownload = (url, fileName = '下载文件') => {
  // 创建隐藏的可下载链接
  let eleLink = document.createElement('a')
  eleLink.download = fileName
  eleLink.style.display = 'none'
  eleLink.href = url
  // 触发点击
  document.body.appendChild(eleLink)
  eleLink.click()
  // 然后移除
  document.body.removeChild(eleLink)
}

8. Laden Sie mehrere Dateien herunter

/**
 * 以iframe的方式实现的多文件下载
 * @param { urls:array } - 需要下载的内容的数组列表,可以只有一条数据。
 */
export const dnLoadMultipleFiles = (urls) => {
  if (typeof urls !== 'object' || urls.length === 0) return
  urls.forEach(item => {
    const iframe = document.createElement('iframe')
    iframe.style.display = 'none' // 防止影响页面
    iframe.style.height = 0 // 防止影响页面
    iframe.src = item
    document.body.appendChild(iframe) // 这一行必须,iframe挂在到dom树上才会发请求
    // 5分钟之后删除(onload方法对于下载链接不起作用,就先这样吧)
    setTimeout(() => {
      iframe.remove()
    }, 5 * 60 * 1000)
  })
}

9. Willkommen zum Austausch und zur Korrektur, zum gemeinsamen Lernen.

10. Referenzlink:

Wie das Front-End den Dateidownload implementiert (sieben Methoden)

Wenn axios anfordert, den Antworttyp auf „blob“ oder „arraybuffer“ zu setzen, um eine Datei herunterzuladen, wird der Fall korrekt behandelt, in dem der Rückgabewert ein Dateistream oder ein JSON-Objekt ist – Blog von Stubborn Little Sheep – CSDN-Blog

Axios-ResponseType-Typ dynamische Einstellung_Jiang Xiaomos Blog-CSDN blog_axios Responsetype

おすすめ

転載: blog.csdn.net/snowball_li/article/details/126657300