首页 > 解决方案 > PHP 文件下载:PHP 正在 ajax 响应中发送文件数据,但文件未下载

问题描述

我有一个HTML允许用户下载文件的页面,有一个下载按钮,我正在使用onClick事件来ajax调用php提供文件数据的脚本。

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

我已经通过 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>

PHP script


public function download() {
        $path = $this->input->post('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);
        }
    }

谢谢。

标签: phpjqueryhtmlajax

解决方案


更改服务器功能,使其使用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);
    }
}

推荐阅读