Files
admin-sjzx/src/utils/fileDownLoad.ts

91 lines
3.5 KiB
TypeScript
Raw Normal View History

import { downloadFile } from '@/api/system-boot/file'
// 下载文件
2025-12-25 13:19:24 +08:00
export const download = (urls: string) => {
2025-12-30 10:02:01 +08:00
//console.log('下载', urls)
2025-12-25 13:19:24 +08:00
downloadFile({ filePath: urls })
.then((res: any) => {
// 1. 确定文件MIME类型优化用更简洁的方式
const getFileType = (url: string) => {
const ext = url.split('.').pop()?.toLowerCase() || ''
const mimeMap: Record<string, string> = {
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] || ''
}
2025-12-30 10:02:01 +08:00
2025-12-25 13:19:24 +08:00
const blob = new Blob([res], { type: getFileType(urls) })
2025-12-30 10:02:01 +08:00
2025-12-25 13:19:24 +08:00
// 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
})
2025-12-19 11:58:26 +08:00
}
function removeLastDotSuffix(str: string) {
// 找到最后一个 . 的位置
const lastDotIndex = str.lastIndexOf('.')
// 如果存在 .,截取到 . 之前的部分;否则返回原字符串
return lastDotIndex !== -1 ? str.slice(0, lastDotIndex) : str
}
// 预览文件
export const previewFile = async (urls: any) => {
2025-12-30 10:02:01 +08:00
//console.log('预览', urls)
let url = ''
2025-12-25 13:19:24 +08:00
await downloadFile({ filePath: decodeURI(urls) })
.then((res: any) => {
// 1. 确定文件MIME类型优化用更简洁的方式
const getFileType = (url: string) => {
const ext = url.split('.').pop()?.toLowerCase() || ''
const mimeMap: Record<string, string> = {
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
})
2025-12-30 10:02:01 +08:00
//console.log('url', url)
return url
}