import { downloadFile } from '@/api/system-boot/file' // 下载文件 export const download = (urls: string) => { //console.log('下载', urls) downloadFile({ filePath: urls }) .then((res: any) => { // 1. 确定文件MIME类型(优化:用更简洁的方式) const getFileType = (url: string) => { const ext = url.split('.').pop()?.toLowerCase() || '' const mimeMap: Record = { pdf: 'application/pdf', zip: 'application/zip', doc: 'application/msword', docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', xls: 'application/vnd.ms-excel', xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', png: 'image/png', jpeg: 'image/jpeg', jpg: 'image/jpg' } return mimeMap[ext] || '' } const blob = new Blob([res], { type: getFileType(urls) }) // 2. 提取文件名并保留原生后缀(核心修复点) const fileName = urls.split('/').at(-1) || '下载文件' // 先提取URL最后一段(文件名) // 3. 创建下载链接 const url = window.URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = fileName // 直接使用原文件名(保留后缀) document.body.appendChild(link) link.click() // 4. 清理资源(优化) link.remove() window.URL.revokeObjectURL(url) // 释放blob URL }) .catch(err => { console.error('下载失败:', err) // 可添加错误提示(如Toast) }) } function removeLastDotSuffix(str: string) { // 找到最后一个 . 的位置 const lastDotIndex = str.lastIndexOf('.') // 如果存在 .,截取到 . 之前的部分;否则返回原字符串 return lastDotIndex !== -1 ? str.slice(0, lastDotIndex) : str } // 预览文件 export const previewFile = async (urls: any) => { //console.log('预览', urls) let url = '' await downloadFile({ filePath: decodeURI(urls) }) .then((res: any) => { // 1. 确定文件MIME类型(优化:用更简洁的方式) const getFileType = (url: string) => { const ext = url.split('.').pop()?.toLowerCase() || '' const mimeMap: Record = { pdf: 'application/pdf', zip: 'application/zip', doc: 'application/msword', docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', xls: 'application/vnd.ms-excel', xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', png: 'image/png', jpeg: 'image/jpeg', jpg: 'image/jpg' } return mimeMap[ext] || '' } const blob = new Blob([res], { type: getFileType(decodeURI(urls)) }) // 3. 创建下载链接 url = window.URL.createObjectURL(blob) }) .catch(err => { console.error('下载失败:', err) // 可添加错误提示(如Toast) }) //console.log('url', url) return url }