前端经常有需求需要下载文件
<!DOCTYPE html>
<html lang="zh-CN">
<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>下载</title>
<script src="./js/FileSaver/FileSaver.js"></script>
<script src="./js/download/download.js"></script>
</head>
<body>
<a href="pdfUrl" download="123.pdf"> A标签下载</a>
<button onclick="jsInaDownload(pdfUrl,'jsInaDownload')"> js创建A标签下载</button>
<button onclick="txtDownload(pdfUrl,'blob')"> blob下载文本信息</button>
<button onclick="imgDownload(imgUrl,'blob')"> blob下载图片</button>
<button onclick="FileSaver(pdfUrl,'FileSaver')"> FileSaver 下载文件</button>
<button onclick="downloadJS(pdfUrl,'downloadJS.pdf')"> downloadJS 下载文件</button>
</body>
<script>
var pdfUrl = "http://111.16.49.14:8090/123.pdf"
var imgUrl = "https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2018/10/25/166ab1b848825d7d~tplv-t2oaga2asx-jj-mark:3024:0:0:0:q75.png"
function jsInaDownload(url,filename){
const link = document.createElement('a')
link.href = url
link.target = '_blank'
link.download = filename
link.style.display = 'none'
document.body.append(link)
link.click()
}
var txtDownload = function (content, filename) {
// 创建隐藏的可下载链接
var eleLink = document.createElement('a');
eleLink.download = filename;
eleLink.style.display = 'none';
// 字符内容转变成blob地址
var blob = new Blob([content]);
eleLink.href = URL.createObjectURL(blob);
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
};
var imgDownload = function (domImg, filename) {
// 创建隐藏的可下载链接
var eleLink = document.createElement('a');
eleLink.download = filename;
eleLink.style.display = 'none';
// 图片转base64地址
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
var width = domImg.naturalWidth;
var height = domImg.naturalHeight; context.drawImage(domImg, 0, 0);
// 如果是PNG图片,则canvas.toDataURL('image/png')
eleLink.href = canvas.toDataURL('image/jpeg');
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
// 然后移除
document.body.removeChild(eleLink);
};
function FileSaver(fileUrl,filename) {
saveAs(fileUrl, filename)
}
function downloadJS(fileUrl,filename){
download(fileUrl, filename);
}
</script>
</html>
暂时,只有这些,后期再更新具体说明