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

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

报告相同问题?

悬赏问题

  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 arduino控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题