1.txt文本文件实现下载而不是在浏览器中打开
对于txt文件发现下面的方法并不适用,ie浏览器会自动打开,通过查找发现通过《download.js》下载download.js,页面引用此js后,直接调用
download("文件路径","文件名称","text/plain")
就可以直接下载txt文件,遗憾的测试之后发现ie8 不支持。本文参考《download.js实现txt在浏览器打开》
1中的方法经测无用,下载的的文件里的内容为第一各参数里的内容。
2.服务端pdf文件实现下载功能
通过用location.href="https://***/33ee.pdf"下载文件时发现有时候IE是不会直接下载,并且谷歌浏览器也不支持,在网上搜到一个js方法可以解决这种问题,试过之后支持谷歌,ie浏览器支持8及以上,总结如下:
js代码:
function downloadFile (sUrl) {
//iOS devices do not support downloading. We have to inform user about this.
if (/(iP)/g.test(navigator.userAgent)) {
alert('Your device does not support files downloading. Please try again in desktop browser.');
return false;
}
//If in Chrome or Safari - download via virtual link click
if (window.downloadFile.isChrome || window.downloadFile.isSafari) {
//Creating new link node.
var link = document.createElement('a');
link.href = sUrl;
if (link.download !== undefined) {
//Set HTML5 download attribute. This will prevent file from opening if supported.
var fileName = sUrl.substring(sUrl.lastIndexOf('/') + 1, sUrl.length);
link.download = fileName;
}
//Dispatching click event.
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
return true;
}
}
// Force file download (whether supported by server).
if (sUrl.indexOf('?') === -1) {
sUrl += '?download';
}
window.open(sUrl, '_self');
return true;
}
window.downloadFile.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
window.downloadFile.isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
调用如下:
function downloadPdf(id) {
var url="https://***/33ee.pdf";//服务器端pdf文件路径
downloadFile(url);
}