douou1872 2015-04-07 12:31
浏览 32
已采纳

使用ajax将具有不同名称的文件下载到存储的名称

I follow what it's write here Downloading a file with a different name to the stored name . But i'm not sur too understand everything because it's don't work when i try do it with ajax. I signal that i use Smarty.

This is my html code :

 // In $attache.id their is the id of the data i want to dowload in the database
 <a href='javascript:uploadAttachFile({- $attache.id -});'><img src='../tools/telecharger.gif' /></a>

This is my jQuery code :

function uploadAttachFile(idAttache)
{
   $.ajax({
      //This permit me to go to the php function
      url: ajaxURL("attacheUpload"),
      type: "POST",
      data: {
         idAttache: idAttache
      },
      success: function(data)
      {
         alert(data);
      }
   })
}

This is my php code :

    //Permit to have the path and new title of the file
    $attacheEntite = Model_AttacheDB::getNameAndPathAttachFile(request('idAttache'));
    $file = 'path' . $attacheEntite['path'];

    if (file_exists($file))
    {
       header('Content-disposition: application/force-download; filename="' .$attacheEntite['titre']. '"');
       header("Content-Type: application/pdf");
       header('Content-Transfer-Encoding: binary');
       header("Content-Length: " . filesize($file));
       header("Pragma: ");
       header("Expires: 0");

       // upload the file to the user and quit
       ob_clean();
       flush();
       readfile($file);
       exit;
   }

I know that it pass by my php code because the ajax reuest pass by succes and alert an incomprehensible code who is certainly the code of the pdf file when i read it.

  • 写回答

1条回答 默认 最新

  • douqin6785 2015-04-07 12:49
    关注

    You can't make the client download the file through an ajax request.

    What you are doing here is reading the file server-side with PHP and returning his content to the caller script ( in fact you see the content in the "data" variable )

    Without ajax, you can call the script like this:

    <a href='path/to/your/phpscript.php' target='_blank' ><img src='../tools/telecharger.gif' /></a>
    

    And it will send the file to the browser

    EDIT: if you add the attribute target="_blank" to the anchor it will open the download in a new tab, without reloading the current page

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致