PHP文件下载:PHP正在ajax响应中发送文件数据,但文件未下载

时间:2019-06-11 01:53:43

标签: php jquery html ajax

我有一个HTML页面,允许用户下载文件,有一个按钮可以下载它,我正在使用onClick事件对{{ 1}}脚本来提供文件数据。

问题是响应中接收到文件数据,但文件未下载。

我已经提到了这篇Php file download through ajax request帖子,但没有解决我的问题

ajax页面

php

HTML


<button onClick="download()"> Download </button>

<script>
    function download {
    var url = "download"; //it is a code ignitor project hence it is just an action call.
    var path ="<?php echo $data[0]->file_path . $data[0]->file_name; ?>";
    $.post(url, {path: path}, function(result){

    });
</script>

谢谢。

1 个答案:

答案 0 :(得分:1)

更改服务器功能,使其使用get参数。然后使用脚本URL打开一个新窗口。

function download() {
    var path ="<?php echo $data[0]->file_path . $data[0]->file_name; ?>";
    var url = "download?path=" + encodeURIComponent(path); //it is a code ignitor project hence it is just an action call.
    window.open(url);
});
public function download() {
    $path = $this->input->get('path');

    if(!file_exists($path)){
        die('file not found');
    } else {
        header("Content-Disposition: attachment; filename=" . basename($path) . "");
        header("Content-Length: " . filesize($path));
        header("Content-Type: application/octet-stream;");
        readfile($path);
    }
}