<commit_before>﻿---
title: "js文件下载"
tags:
  - Articles
---

### 解析数据

首先基于 axios 插件的 http 请求, 设置 xhr.responseType = 'blob'格式, 接收后端返回的数据流.

```bash
const handleLoadingFile = (dataStream:any, fallback: Function) => {
  const getBlobData = (blob:any,fallback:Function) =>{
    const fr = new FileReader()
    fr.onload= function (ev) {
      fallback(ev.targe.result)
    }
    fr.readAsDataURL(resBlobdata)
  }
  getBlobData(dataStream, (value: any) => {
    if(value) fallback(value)
  })
}
```

### 读取并下载数据

在封装了上面的接收数据流的同时读取结果数据, 然后把结果数据通过回调函数进行输出下载.

```bash
import axios from 'axios'

axios('172.16.58.3').then((res:any) => {
  handleLoadingFile(res.data, function (value: any) {
    try{
      let link = document.createElement('a')
      let filename = res.headers['content-disposition'].split('=')
      filename = filename[filename.length - 1]
      filename = decodeURI(filename.replace(/"/g, ''))
      link.download = record.filename
      link.href = value
      document.body.appendChild(link)
      link.click()
      document.body.appendChild(link)
    }catch(err) {
      console.log(err)
    }
  })
})
```<commit_msg>文章-文件下载2<commit_after>﻿---
title: "js文件下载"
tags:
  - Articles
---

### 解析数据

首先基于 axios 插件的 http 请求, 设置 xhr.responseType = 'blob'格式, 接收后端返回的数据流.

```bash
const handleLoadingFile = (dataStream:any, fallback: Function) => {
  const getBlobData = (blob:any,fallback:Function) =>{
    const fr = new FileReader()
    fr.onload= function (ev) {
      fallback(ev.targe.result)
    }
    fr.readAsDataURL(resBlobdata)
  }
  getBlobData(dataStream, (value: any) => {
    if(value) fallback(value)
  })
}
```

### 读取并下载数据

在封装了上面的接收数据流的同时读取结果数据, 然后把结果数据通过回调函数进行输出下载.

```bash
import axios from 'axios'

axios('172.16.58.3').then((res:any) => {
  handleLoadingFile(res.data, function (value: any) {
    try{
      let link = document.createElement('a')
      let filename = res.headers['content-disposition'].split('=')
      filename = filename[filename.length - 1]
      filename = decodeURI(filename.replace(/"/g, ''))
      link.download = record.filename
      link.href = value
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }catch(err) {
      console.log(err)
    }
  })
})
```
{'fraction_non_alphanumeric': 0.16054842989827509, 'fraction_numerical': 0.008403361344537815, 'mean_word_length': 3.300380228136882, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6703071', 'n_tokens_mistral': 913, 'n_tokens_neox': 921, 'n_words': 144}