前端AXIOS文件流下载工具

125 阅读1分钟

封装的一个文件流下载工具

/* 
*调用示例
*/
// excelExport({ ...params }).then((res) => {
//   downloadFromFileStream(res, fileNameFactory(`供应商用户管理`, {
//       prepend: true,
//       append: false
//     }), `application/vnd.ms-excel`)
// })


```js
// 下载文件流
export const downloadFromFileStream = (fileStream, fileName, type) => {
  const blob = new Blob([fileStream], {type})
  const objectUrl = URL.createObjectURL(blob)
  const link = document.createElement("a")
  link.href = objectUrl
  link.setAttribute("download", fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 生成下载文件的文件名
export const fileNameFactory = (name, option = {prepend: true, append: true}) => {
  const date = new Date()
  const year = date.getFullYear().toString()
  const month = (date.getMonth() + 1).toString().length === 1 ? '0' + (date.getMonth() + 1).toString() : (date.getMonth() + 1).toString()
  const day = date.getDate().toString().length === 1 ? '0' + date.getDate().toString() : date.getDate().toString()
  const hour = date.getHours().toString().length === 1 ? '0' + date.getHours().toString() : date.getHours().toString()
  const minutes = date.getMinutes().toString().length === 1 ? '0' + date.getMinutes().toString() : date.getMinutes().toString()

  const {prepend, append} = option

  if (prepend) name = `${year}${month}${day}` + name//文件名前加时间戳
  if (append) name += `${hour}点${minutes}分`//文件名后加

  return name
}