如何从服务器或本地xampp下载文件? php

问题描述:

我想下载一个.pptx文件从我的站点文件夹下载或获取保存弹出,用户可以选择保存文件夹。但是当我打电话给我的功能时,它在console.log中打印了一个内容。如何从服务器或本地xampp下载文件? php

我已经使用不同的代码,但没有人工作。

PK����Uy�G��-j����P����_rels/.rels���������������������JA��>Ő{w�D��^D�Md}�0���;3!�}{���B)��������l>Hʔ��uӂ��s�����{Z݃)�)��98Q��n�B3j])���TF*FU~����"�&3�:��D�Z�`�d7m{g�'�Ls��`����6�[email protected]��Њ�n�N�ӡ�B�ϵ]Ή���^��^(����1��HI/y�Q) 

ו-2 jY9%dPKUyGI + docProps /core.xml m j @E ;-; RL J! 4 3 ����wb���R�sW���O�gq1�5-T(Z��ߞ�'�DM�f���e��~G�����c⬎�*� =�Ϊ�G:�7�"��3fo��y�d�ˌ���}D�j�Q�Wa�V#�+-�����Eyb A -..... 还有更多。

这是我的代码:

 function downloadProject($file, $db) 
     { 
      $path = "../assets/convertables/Presentaties/"; // change the path to fit your websites document structure 
      $dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\].]|[\.]{2,})", '', $file.'.pptx'); // simple file name validation 
      $dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters 
      $fullPath = $path.$dl_file; 
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
      header('Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation'); 
      header("Content-Transfer-Encoding: Binary"); 
      header("Content-length: ".filesize($fullPath)); 
      header("Content-disposition: attachment; filename=\"".$dl_file."\""); 
      readfile($fullPath);   
     } 

编辑:我已经检查与解答其他问题,但并没有为我工作!

+0

我怎样才能投票你的评论.... – TheJokerAeZ

+0

有没有办法@TheJokerAez,我会删除这个不要担心 – devpro

你可以试试这个:

首先,你需要定义下载文件

的正确的MIME类型/内容类型在你的情况是:应用程序/ vnd.ms - PowerPoint中

所以代码会:

$mime = 'application/vnd.ms-powerpoint'; 

    // Generate the server headers 
    if(strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) //id browser is IE 
    { 
     header('Content-Type: "'. $mime .'"'); 
     header('Content-Disposition: attachment; filename="'.$filename.'"'); 
     header('Expires: 0'); 
     header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
     header("Content-Transfer-Encoding: binary"); 
     header('Pragma: public'); 
     header("Content-Length: ".filesize($data)); 
    } 
    else 
    { 
     header("Pragma: public"); 
     header("Expires: 0"); 
     header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
     header("Cache-Control: private", false); 
     header("Content-Type: ".$mime, true, 200); 
     header('Content-Length: '.filesize($data)); 
     header('Content-Disposition: attachment; filename='.$filename); 
     header("Content-Transfer-Encoding: binary"); 
    } 
    readfile($data); 
    exit; 

您可以了解更多的网站在http://www.phpdevtips.com/snippets/force-file-download-with-correct-content-type/

+0

下载文件在哪里去?我的ajax请求发送成功,但我看不到任何下载。 – TheJokerAeZ

+0

哦。你正在使用ajax ...所以我有想法:你可以使用ajax打开新的浏览器窗口(或标签)与充满下载URL或使用document.location(download_url); – GiapLee

+0

我发送所选行名称的ID,并在PHP中,我得到这个名称与$ _post。我和班级和职能一起工作 – TheJokerAeZ