import { convert } from '../utils/base64-to-blob' import { showLoading, removeLoading } from '../utils/request' import { Message } from 'element-ui' import i18n from '../lang' export const downloadFile = (response: any, name = '') => { let blob if (response.data) { blob = response.data } else { blob = convert(response) } const url = window.URL.createObjectURL(blob) const link = document.createElement('a') link.setAttribute('type', 'hidden') link.download = name || getFileNameFromHttpResponse(response) link.href = url document.body.appendChild(link) link.click() link.remove() } function getFileNameFromHttpResponse(httpResponse: any) { try { const contentDispositionHeader = httpResponse.headers['content-disposition'] const result = contentDispositionHeader.split(';')[1].trim().split('=')[1] return decodeURIComponent(result.replace(/"/g, '')) } catch { return 'excel.xlsx' } } export const readPdfFile = async(data: any) => { return new Promise((resolve) => { const reader = new FileReader() reader.readAsDataURL(data) reader.onload = (event: any) => { let d = event.target.result d = d.replace('data:text/xml', 'data:application/pdf') resolve(d) } }) } export const downloadFileFromURL = async( file: string, name: string, loading = true, download = true ) => { if (loading) { showLoading() } try { const response = await fetch(file, { method: 'GET', mode: 'cors', cache: 'no-cache', credentials: 'same-origin' }) const blob: any = await response.blob() if (blob) { if (loading) { removeLoading() } if (download) { downloadFile({ data: blob }, name) } else { return blob } } } catch (err) { removeLoading() Message({ dangerouslyUseHTMLString: true, message: err + `. ${i18n.t('general.tryAgainLater')}`, type: 'error', duration: 3 * 1000, showClose: true }) } }