Skip to content

Instantly share code, notes, and snippets.

@giscafer
Last active April 28, 2018 05:38
Show Gist options
  • Save giscafer/fe160eafbf7ef717436d3fcc8d2e75be to your computer and use it in GitHub Desktop.
Save giscafer/fe160eafbf7ef717436d3fcc8d2e75be to your computer and use it in GitHub Desktop.
文件下载
/**
* 下载统一接口,判断浏览器是否支持a标签download属性,如果不支持采用form表单提交方式下载文件
* @param url
* @param fileName
*/
export function download(url: string, fileName?: string) {
const isSupportDownload = 'download' in document.createElement('a');
if (isSupportDownload) {
downloadByLink(url, fileName);
} else {
downloadByForm(url);
}
}
/**
* 根据url直接下载文件(IE10+ 浏览器)
* @param url 文件地址
* @param fileName 自定义下载文件名称(必须有文件名后缀,比如图片就 picture.jpg,excel文档就为:模板.xls)
* 不过这里的文件名目前可能受到浏览器兼容性的影响,一些浏览器可能需要通过右键文件另存为才可以自定义文件名称。
*/
function downloadByLink(url: string, fileName?: string) {
if (!url) {
return;
}
let eleA = document.createElement('a');
eleA.style.display = 'none';
eleA.href = url;
eleA.nodeValue = '下载'+fileName;
eleA.setAttribute('download', fileName || '模板.xls');
document.body.appendChild(eleA);
eleA.click();
document.body.removeChild(eleA)
}
/**
* 根据url直接下载文件
* 不好的地方是不能更改下载文件的文件名称,如http://yztfile.gz.bcebos.com/WMGb-cvmXnwLHOIj.xls 下载的文件为 WMGb-cvmXnwLHOIj.xls
* @param url
*/
function downloadByForm(url: string) {
if (!url) {
return;
}
let eleForm = document.createElement('form');
eleForm.method = "GET";
eleForm.style.display = 'none';
eleForm.action = url;
document.body.appendChild(eleForm);
eleForm.submit();
document.body.removeChild(eleForm)
}
/**
* 内容下载
* @param content 文件内容
* @param fileName 文件名称
*/
export function downloadContent(content, fileName?: string) {
let eleLink = document.createElement('a');
eleLink.download = fileName || '下载.html';
eleLink.style.display = 'none';
let blob = new Blob([content]);
eleLink.href = URL.createObjectURL(blob);
document.body.appendChild(eleLink);
eleLink.click();
document.body.removeChild(eleLink);
}
/**
* 打开空白页下载文件(体验差,或者文本的文件可能直接浏览器打开。不推荐使用)
* @param url
*/
export function openByUrl(url: string) {
if (!url) {
return;
}
window.open(url);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment