当前位置:   article > 正文

前端文件下载方式总结_文件下载传params参数

文件下载传params参数

平时开发中我们很多时候都会要用到文件下载,所以总结了一下平时常用得一些下载方法。

1、文件流二进制

// 在请求的时候加上getResponse 为true ,这样就可以得到头部信息,通过头部信息就可以拿到后台返回得文件名

/**
 * @param  {String} res 二进制流
 * @param  {String} name下载文件名称(可传可不传)
 */
export function use_flow_download(res: any, name?: string) {
  if (!data) {
    return;
  }
  let fileName = ""
  const hs = res.headers.get('content-disposition');
  if (hs) {
 	const reg = /filename=(.*)/;
  	fileName = name||reg.exec(hs)[1].trim();
  }
  const url = window.URL.createObjectURL(new Blob([res.data]));
  const link = document.createElement('a');
  link.style.display = 'none';
  link.href = url;
  link.setAttribute('download', `${fileName}`);
  document.body.appendChild(link);
  link.click();

	

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

2、通过 form 下载文件(支持post传参)

/**
 * @param  {String} method http method
 * @param  {String} action 后端接口
 * @param  {Object} params 请求参数
 */
export async function use_form_download(method: string, action: string, params: any = {}) {
  const inputs = Object.keys(params)
    .map((key) => {
      return `<input type='hidden' name='${key}' value='${params[key]}'/>`;
    })
    .join('');
  const $form = document.createElement('form');
  $form.action = action;
  $form.method = method;
  $form.innerHTML = inputs;
  document.body.appendChild($form);
  $form.submit();
  setTimeout(() => {
  	$form.remove();
  }, 10000);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

3、通过 iframe 下载文件

/**
 * @param  {String } download_path 需下载文件的链接
 */
 export async function use_iframe_download(download_path: string) {
  const $iframe = document.createElement('iframe');
  $iframe.style.height = '0px';
  $iframe.style.width = '0px';
  document.body.appendChild($iframe);
  $iframe.setAttribute('src', download_path);
  setTimeout(() => {
   $iframe.remove();
  }, 20000);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

4、通过 a标签下载文件

/**
 * @param  {String } download_path 需下载文件的链接
 */
export function use_a_download(download_path: string) {
  const $a = document.createElement('a');
  document.body.appendChild($a);
  $a.href = download_path;
  $a.download = 'download';
  $a.click();
  setTimeout(() => {
    $a.remove();
  }, 20000);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

5、window.open下载文件

window.open('file/test.xls');
  • 1

6、文件下载带参数

url = '/api/software-manager/download' + '?token=' + Token.get()
  • 1
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/770348
推荐阅读
相关标签
  

闽ICP备14008679号