在实际工作中,有时候我们需要将txt文件作为附件下载,而不是将他打开。而浏览器默认行为是打开txt文件,所以我们要通过一定技术手段将文件直接弹出下载。
第一种方法:利用php代码指定header来实现
<?php
header("Content-type:application/octet-stream");
header("Accept-Ranges:bytes");
header("Accept-Length:".filesize($file_path));
header("Content-Disposition:attachment;filename=".$file_name);
$fp=fopen($file_path,"r");
echo fread($fp,filesize($file_path));
fclose($fp);
?>
------------------------------------------------------------
$fp = fopen($csvfileLoad,"r");
$fsize = filesize($csvfileLoad);
$SaveName = str_replace("csv/","",$csvfileLoad);
header("Content-type: application/download\r\n");
header("Content-length: $fsize\r\n");
header("Content-disposition-type: attachment\r\n");
header("Content-disposition: filename=$SaveName");
$result = fpassthru($fp);
第二种,在IIS中的mime文件类型里或其他服务器环境中,强制把txt文件指定为application/octet-stream类型。
第三种,使用JavaScript代码来处理。
<a href="#" onclick="openfile()">下载</a>
<script language="JavaScript">
function openfile() {
var a = window.open("*.txt","_blank");
a.document.execCommand("SaveAs");
a.close();
}
</script>在nginx中,可以这样
location /
{
if ($request_filename ~* ^.*?\.(pdf|doc)$){
add_header Content-Disposition: 'attachment;';
}
types {
application/octet-stream pdf;
application/octet-stream doc;
application/octet-stream ipa apk;
}
}
¥ 1.88微信扫描即可打赏
服务器好贵
网站需要运营
给点小费以表支持
评论已关闭