mirror of
https://github.com/continew-org/continew-admin-ui.git
synced 2025-09-09 08:57:14 +08:00
fix: 修复文件无法直接下载问题
Closes continew/continew-admin#IBF2YB
This commit is contained in:
@@ -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
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
Reference in New Issue
Block a user