美文网首页
js文件导出(下载)

js文件导出(下载)

作者: Lethe35 | 来源:发表于2019-01-07 11:41 被阅读0次
duorouzhiwu-004.jpg

1. 当下载的文件不是存在服务器上的静态文件 需要调用后台API生成

1) GET方法

通过创建隐藏的iframe实现

export async function downloadFile(params = {}) {
  const { requestUrl: url, queryParams } = params;
  const newUrl = !url.startsWith('/api') && !url.startsWith('http') ? `${API_HOST}${url}` : url;
  const iframeName = `${url}${Math.random()}`;

  // 构建iframe
  const iframe = document.createElement('iframe');
  iframe.setAttribute('name', iframeName);
  iframe.setAttribute('id', iframeName);
  iframe.style.width = '0px';
  iframe.style.height = '0px';
  iframe.style.display = 'none';

  // 构建form
  const downloadForm = document.createElement('form');
  // form 指向 iframe
  downloadForm.setAttribute('target', iframeName);

  // 设置token
  const tokenInput = document.createElement('input');
  tokenInput.setAttribute('type', 'hidden');
  tokenInput.setAttribute('name', 'access_token');
  tokenInput.setAttribute('value', `${getAccessToken()}`);

  // 表单添加请求配置
  downloadForm.setAttribute('method', params.method);
  downloadForm.setAttribute('action', newUrl);
  downloadForm.appendChild(tokenInput);

  // 表单添加查询参数
  if (queryParams && Array.isArray(queryParams)) {
    queryParams.forEach(item => {
      const input = document.createElement('input');
      input.setAttribute('type', 'hidden');
      input.setAttribute('name', item.name);
      input.setAttribute('value', item.value);
      downloadForm.appendChild(input);
    });
  }

  document.body.appendChild(iframe);
  document.body.appendChild(downloadForm);
  downloadForm.submit();

  // setTimeout(() => {
  //   document.body.removeChild(downloadForm);
  //   document.body.removeChild(iframe);
  // }, 2500);
  return true;
}

// 调用
params.push({ name: 'exportType', value: 'DATA' });
params.push({ name: 'fillerType', value: fillerType });
downloadFile({ requestUrl, queryParams: params, method }).then(res => {
  if (res) {
    this.setState({ exportPending: false });
  }
});

2) POST方法

// 1.
handleExportResult() {
  const { sqlExecute: { exportSql } } = this.props;
  const requestUrl = `${apiPrefix}/v1/db-ide/export`;

  if (exportSql) {
    this.setState({ exportPending: true });
    request(requestUrl, {
      method: 'POST',
      body: { sql: exportSql },
      responseType: 'blob',
    })
      .then(blob => {
        // 创建隐藏的可下载链接
        const eleLink = document.createElement('a');
        eleLink.download = 'SQL导出结果.xlsx';
        eleLink.style.display = 'none';
        eleLink.href = window.URL.createObjectURL(blob);
        // 触发点击
        document.body.appendChild(eleLink);
        eleLink.click();
        // 然后移除
        document.body.removeChild(eleLink);
        this.setState({
          exportPending: false,
        });
      })
      .catch(error => {
        notification.error({
          description: error,
        });
        this.setState({
          exportPending: false,
        });
      });
  }
}



//2.
request(requestUrl, {
  method: 'GET',
  // query: params,
  responseType: 'response',
})
.then(res => res.blob().then(blob => {
  const fileName = res.headers.get('Content-Disposition') && res.headers.get('Content-Disposition').split(";")[1].split("filename=")[1] || '报表导出结果';
  if ('msSaveOrOpenBlob' in navigator) { // IE导出
      window.navigator.msSaveOrOpenBlob(blob, fileName);
  }else{
    const eleLink = document.createElement('a');
    eleLink.download = fileName;
    eleLink.style.display = 'none';
    eleLink.href = window.URL.createObjectURL(blob);
    // 触发点击
    document.body.appendChild(eleLink);
    eleLink.click();
    // 然后移除
    document.body.removeChild(eleLink);
    this.setState({
      // exportLoading: false,
    });
  }
}))
.catch(error => {
  notification.error({
    description: error,
  });
  this.setState({
    // exportLoading: false,
  });
});

2.当下载的文件是静态文件

<a href="/user/test/xxxx.txt" download="文件名.txt">点击下载</a> 

3.本地下载(xml文件)

  getExportFile() {
    const { xmlSampleContent = {}, datasetCode } = this.props;
    if (!isUndefined(xmlSampleContent.content)) {
      const d = new Blob([xmlSampleContent.content], { type: 'xml' });
      const objectURL = window.URL.createObjectURL(d);

      const link = document.createElement('a');
      // 触发点击
      link.href = objectURL;
      link.download = `${datasetCode}.xml`;
      link.click();
    }
  }

相关文章

网友评论

      本文标题:js文件导出(下载)

      本文链接:https://www.haomeiwen.com/subject/ifmbhqtx.html