Skip to content

Commit

Permalink
fix: 修复文件无法直接下载问题
Browse files Browse the repository at this point in the history
Closes continew/continew-admin#IBF2YB
  • Loading branch information
Charles7c committed Jan 2, 2025
1 parent b98febc commit 91092f1
Showing 1 changed file with 19 additions and 31 deletions.
50 changes: 19 additions & 31 deletions src/utils/downloadFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ export function downloadByUrl({
}): Promise<boolean> {
// 是否同源
const isSameHost = new URL(url).host === location.host
return new Promise<boolean>((resolve) => {
return new Promise<boolean>((resolve, reject) => {
if (isSameHost) {
// 同源资源,直接使用 <a> 标签下载
const link = document.createElement('a')
link.href = url
link.target = target
Expand All @@ -49,36 +50,23 @@ export function downloadByUrl({
window.open(url, target)
return resolve(true)
} else {
const elink = document.createElement('a')
elink.href = url
elink.target = '_self'
elink.download = fileName as string
elink.style.display = 'none'
document.body.appendChild(elink)
elink.click()
document.body.removeChild(elink)
// const canvas = document.createElement('canvas')
// const img = document.createElement('img')
// img.setAttribute('crossOrigin', 'Anonymous')
// img.src = url
// img.onload = () => {
// canvas.width = img.width
// canvas.height = img.height
// const context = canvas.getContext('2d')!
// context.drawImage(img, 0, 0, img.width, img.height)
// // window.navigator.msSaveBlob(canvas.msToBlob(),'image.jpg');
// // saveAs(imageDataUrl, '附件');
// canvas.toBlob((blob) => {
// const link = document.createElement('a')
// if (!blob) return
// link.href = window.URL.createObjectURL(blob)
// link.download = fileName || getFileName(url)
// link.click()
// URL.revokeObjectURL(link.href)
// resolve(true)
// }, 'image/jpeg')
// }
// img.onerror = (e) => reject(e)
// 跨域资源,使用 fetch 获取文件并下载
fetch(url)
.then((response) => response.blob())
.then((blob) => {
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = fileName || getFileName(url)
link.style.display = 'none'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
URL.revokeObjectURL(link.href)
resolve(true)
})
.catch((err) => {
reject(err)
})
}
})
}

0 comments on commit 91092f1

Please sign in to comment.