web文件下载,a标签文件下载,php文件下载

文件下载的方式

  目的:解决下载文件预览的问题

  (1) 禁止浏览器默认支持的预览图片,文本功能。

1. a标签文件下载

  (1) window.location.href=’文件地址’

  (2) H5新增属性 download

  ① 写法 Download=”文件名称”;

  ② 支持浏览器 火狐,谷歌,不支持浏览器IE,苹果,欧朋。

2. Php文件下载

  (1) window.location.href="/download.html?file=’文件地址或者要下载的那个数据的id’;

  (2) php文件的内容

    //得到文件的名称

    $file = Yii::$app->request->get("file");

    //判断有没有http,没有的话加上域名。

    if (!preg_match('/(http://)|(https://)/i', $file)) {

           $file = 'http://demo14.szloyi.com'.$file;

    }

    //分隔文件地址,得到文件名称$filename

    $arr=explode("/",$file);

    if(!empty($arr[5])){

              $filename=$arr[5];

       }else{

            $filename=$file;

    }

    //置顶header

    header("Content-type: text/plain");

    header("Accept-Ranges: bytes");

    //设置文件名称

    header("Content-Disposition: attachment; filename=".$filename);

    header("Cache-Control: must-revalidate, post-check=0, pre-check=0" );

    header("Pragma: no-cache" );

    header("Expires: 0");

    //加载文件内容

    readfile($file);

3 . Js文件下载

    (1) IE可以使用iframe进行下载文件,其他可以使用新开页面下载文件。

  1. 常见问题与bug

    (1) Readfile 没写,导致下载的文件都是0KB

4.总结

    (1) A标签下载支持不太好

    (2) Js下载太繁琐,并且不是所有文件都能下载

    (3) 后台处理最简单,方便,省时间

一个96年的PHPER
原文地址:https://www.cnblogs.com/zhouxiaohei/p/12697012.html