a标签下载功能(同域和跨域)
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>
<a href="/04-a标签下载功能/test.png" download="demo">下载</a>
<div onclick="download()">下载</div>
<div onclick="download1()">下载</div>
</div>
<script>
function download(
url = '/04-a标签下载功能/test.png',
title = 'demo2',
artist = 'down'
) {
const eleLink = document.createElement('a')
eleLink.href = url || '/04-a标签下载功能/test.png'
eleLink.download = `${title} - ${artist}`
eleLink.style.display = 'none'
document.body.appendChild(eleLink)
eleLink.click()
document.body.removeChild(eleLink)
}
function download1(
url = 'https://upload-images.jianshu.io/upload_images/5809200-a99419bb94924e6d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240',
title = 'demo3',
artist = 'down'
) {
var x = new XMLHttpRequest()
x.open('GET', url, true)
x.responseType = 'blob'
x.onload = function () {
const url = window.URL.createObjectURL(x.response)
const eleLink = document.createElement('a')
eleLink.href = url
eleLink.download = `${title} - ${artist}`
eleLink.style.display = 'none'
document.body.appendChild(eleLink)
eleLink.click()
document.body.removeChild(eleLink)
}
x.send()
}
</script>
</body>
</html>