接口返回的是数据格式tmplFileUrl:"http://--------/images/cf0a72b3b6ba4c9cb79d3b063bbbed4b.docx"
javascript
// 下载图片,pdf,word,exlce文件
const handleDownload = (record: RecordType) => {
const fileUrl = record.tmplFileUrl
if (fileUrl) {
const downloadUrl = getPreviewUrlHandler(fileUrl) || ''
if (downloadUrl) {
// 从 tmplFileUrl 中提取文件名和类型
const fileName = fileUrl.split('/').pop() || record.tmplName || 'download'
const fileExtension = fileName.split('.').pop()?.toLowerCase() || ''
// 根据文件扩展名判断文件类型
const isImageFile = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(fileExtension)
const isPdfFile = fileExtension === 'pdf'
const isWordFile = ['doc', 'docx'].includes(fileExtension)
const isExcelFile = ['xls', 'xlsx'].includes(fileExtension)
if (isImageFile) {
// 图片文件:使用当前下载逻辑,直接下载到本地
const link = document.createElement('a')
link.href = downloadUrl
link.download = fileName
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} else {
// 附件文件:强制下载,不打开预览
const link = document.createElement('a')
link.href = downloadUrl
link.download = fileName
// 强制下载,防止浏览器打开预览
link.style.display = 'none'
if (isPdfFile) {
// 对于 PDF 文件,添加额外的强制下载处理
fetch(downloadUrl)
.then((response) => response.blob())
.then((blob) => {
const url = window.URL.createObjectURL(blob)
link.href = url
link.download = fileName
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
// 清理 blob URL
window.URL.revokeObjectURL(url)
})
.catch((error) => {
console.error('PDF 下载失败:', error)
// 如果 fetch 失败,回退到普通下载方式
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
} else if (isWordFile || isExcelFile) {
// 对于 Word 和 Excel 文件,使用 fetch 方式下载以提升性能
fetch(downloadUrl)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
return response.blob()
})
.then((blob) => {
const url = window.URL.createObjectURL(blob)
link.href = url
link.download = fileName
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
// 清理 blob URL
window.URL.revokeObjectURL(url)
})
.catch((error) => {
console.error('文件下载失败:', error)
// 如果 fetch 失败,回退到普通下载方式
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
})
} else {
// 其他文件使用普通下载方式
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
}
}
}

简单记录下下载通用函数哈!