/*
|
* @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()
|
}
|