【问题标题】:Trying to download file from remote server using Ajax with Codeigniter not working尝试使用 Ajax 从远程服务器下载文件,但 Codeigniter 不起作用
【发布时间】:2018-01-03 09:26:29
【问题描述】:

点击链接时,我正在尝试下载 pdf。

我调用了链接的 onlick 函数,在 Codeigniter 中我编写了一个下载 PDF 文件的函数,但是在运行 URL 时,文件被下载,但是当使用点击链接触发时,它不起作用。

控制器:

function downloadpdf($pid)
{ set_time_limit(0);

    $url="http://www.malayatourism.com/uploads/images/packages/pdf/$pid.pdf";


$file = basename($url);

$fp = fopen($file, 'w');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
echo "success";
}

我的代码 ajax:

function DownLoadPdf(id)
 {


     url = "<?php echo base_url();?>admin/packages/downloadpdf/"+id;
  $.ajax({

     type:'POST',
     url: url,
     data : { pid : id},

    success : function(response) {
       console.log(response);
    },
    error : function(response) {
         console.log("error");
    }
});
}

查看:

echo '<a  href="javascript:void()" title="Hapus" onclick="DownLoadPdf(' . "'" . $cdata[0]->package_id . "'" . ')"> Download Attachment</a>';

【问题讨论】:

标签: javascript php jquery file download


【解决方案1】:

就 ajax 而言,您不能通过 ajax 做到这一点,因为 ajax 不是为此目的而制作的,它是一个异步调用,会给您一个结果。但是你可以在不使用任何 jquery、ajax 的情况下做到这一点

&lt;a href="http://www.malayatourism.com/uploads/images/packages/pdf/$pid.pdf" download&gt; Download Attachment&lt;/a&gt;

其中 $pid 是您要下载文件的 id。下载属性将强制文件下载。干杯

【讨论】:

    猜你喜欢
    • 2017-12-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 2020-02-29
    • 2016-05-24
    • 2018-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多