Bang Hu
2 天以前 b3fedd4221b807a07058be9d5d5d8ba8998adbcb
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
 * @Description: 
 * @Version: 2.0
 * @Autor: wuyun
 * @Date: 2023-02-20 17:24:05
 * @LastEditors: wuyun
 * @LastEditTime: 2023-02-20 17:44:17
 */
 
// 文件流处理封装
import fileApi from '@/api/commonApi'
// fileId:文件ID, type:使用类型,preview:预览,download:下载
export function useFileDownload(data:any, fileName: any, type: string, fileSuffix?: string) {
  const blobTypes = [
    {
      type: 'xls',
      typeVal: 'application/vnd.ms-excel'
    },
    {
      type: 'xlsx',
      typeVal: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    },
    {
      type: 'doc',
      typeVal: 'application/msword'
    },
    {
      type: 'docx',
      typeVal: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    },
    {
      type: 'pdf',
      typeVal: 'application/pdf'
    },
    {
      type: 'png',
      typeVal: 'image/png'
    },
    {
      type: 'gif',
      typeVal: 'image/gif'
    },
    {
      type: 'jpeg',
      typeVal: 'image/jpeg'
    },
    {
      type: 'jpg',
      typeVal: 'image/jpeg'
    }
  ]
  const fileType = fileSuffix?.split('.')[1] ?? fileName.split('.')[fileName.split('.').length - 1]
  const blobType = blobTypes.find((blType) => {
    return blType.type == fileType
  })?.typeVal
 
  // 获取文件流
  const getFile = () => {
    fileApi.getFileFlowById(data).then((res:any) => {
      if (type == 'download') {
        return downloadFile(res, fileName, blobType)
      } else {
        return previewFile(res, fileName, blobType)
      }
    }).catch(err => {
    })
  }
  // 文件流转换
  const previewFile = (res: any, fileName: string, type: any) => {
    const blob = new Blob([res], {
      type: type
    })
    const URL = window.URL || window.webkitURL
    const fileURL = URL.createObjectURL(blob)
    const fileTypeList = ['doc', 'docx']
    if (!fileTypeList.includes(fileType)) {
      window.open(fileURL);
    }
  }
 
  // 下载文件
  // res 是返回的文件流,type 是文件MIME类型, fileName 是给下载的文件一个名称
  const downloadFile = (res: any, fileName: string, type: any) => {
    const blob = new Blob([res], {
      type: type
    })
    const a = document.createElement('a')
    const URL = window.URL || window.webkitURL
    const herf = URL.createObjectURL(blob)
    a.href = herf
    a.download = fileName
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(herf)
  }
  return getFile()
}