Before php plugin has been used to complete the file download function, see the project code today, to see can be downloaded through the download of a property, the code is as follows:
html part of the code:
<a onclick='downloadData'>download</a>
js part of the code:
function downloadData(){
// 使用a的download属性下载文件
var filename = '文件名称';
var data = '数据';
var blob = new Blob([data],{type:'application/vnd.ms-excel'})
var a = document.createElement('a');//创建a元素
a.href = URL.createObjectURL(blob);
a.download = filename;
a.click();//触发a的点击事件
//URL.revokeObjectUrl(a.href)
a = null;
}
chrome Use this code to run properly on and download the file; but for use on firefox, can not download the file.
Phpexcel had wanted to use plug-ins to rewrite this function, think about it, after all, the project requires not so high, and then look for or have any good solutions.
Just find a way tried, modify the code as follows (using the code rewrite jq no effect, Firefox can not trigger a click event):
<a onclick='downloadData'>download</a>
<a id='dd' style='display:none;'></a>
//以下使用jq写法,使用前请先引入jQuery。
function downloadData(){
var filename = '文件名称';
var data = '数据';
var blob = new Blob([data],{type:'application/vnd.ms-excel'})
$('#dd').attr('href',URL.createObjectURL(blob));
$('#dd').attr('download',filename);
$('#dd').trigger('click');
}
Continue to look for other ways, as follows (not found error message looks like Firefox):
<a onclick='downloadData'>download</a>
function downloadData(){
var data = '数据';
var blob = new Blob([data],{type:'application/vnd.ms-excel'})
var a = document.createElement('a');//创建元素
var event = new MouseEvent('click');
a.download = '文件名称';
a.href = URL.createObjectURL(blob);
a.target = '_blank';
a.dispatchEvent(event);//分发事件
}
Next, to determine the type of browser through window.navigator.userAgent, for example, to determine whether the Firefox browser:
var explorer =window.navigator.userAgent ;if(explorer.indexOf("Firefox")>=0){return '火狐';}
Reference https://segmentfault.com/q/1010000011634405/a-1020000011684880