总结自己近期用到过的实现下载的几种方式
1. a 标签 download 属性
a. <a href = "test.txt" download></a>
b.还可以指定下载文件的名称
<a href = "test.txt" download = 'test_download'>Download</a>
非跨域请求的话三个浏览器火狐 谷歌 IE 都支持 download,但是如果是跨域的情况火狐是不支持的
可以用 JS 来判断是否浏览器支持 download
var isSupportDownload = 'download' in document.createElement('a');
2. 使用 js 的一个插件 Excellentexport
下载地址地址:https://github.com/jmaister/excellentexport
主要是讲界面上的表格导入到 Excel 中并下载
<a href = "" download="dataTest.xls" onclick="return ExcellentExport.excel(this, 'dataTable', 'Sheet Name Here')">
Export to Excel
</a>
<table id = "dataTable">
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
</tr>
<tr>
<td>100 111</td>
<td>200</td>
<td>300</td>
<td>test\ttest</td>
</tr>
</table>
3. PHP 下载
<?php
header("Content-Type:text/html; charset=utf-8");
$fileName = "test.txt";
//$file_name = iconv("utf-8", "gb2312", $file_name);//当文件名为中文时需要对其进行字符编码转换
$fileSubPath="./";
$filePath = $fileSubPath.$fileName;
if(!file_exists($filePath)) {
echo "cannot find this file";
return;
}
$fp = fopen($filePath, "r");
$fileSize = filesize($filePath);
//一下四个 header 必须有
header("Content-Type:application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: $fileSize");
header("Content-Disposition: attachment; filename=".$fileName);
$buffer = 1024;
$fileCount = 0;
while(!feof($fp) && $fileCount < $fileSize){
$fileContent = fread($fp, $buffer);
$fileCount += $buffer;
echo $fileContent;
}
fclose($fp);
?>
iconv ( string $in_charset
, string $out_charset
, string $str
) : string