我不能下载文件强制下载不工作如何修复和下载文件


i can't download file force download not working how to fix and download file

我无法下载文件。我试图通过Ajax从服务器下载文件。我在Ajax数据和响应文件中得到了成功的响应,但文件没有下载我做什么以及如何解决这个问题。文件读取成功,服务器路径也正确。请帮帮我。

这是一个java脚本,当我调用函数和得到响应抛出ajax

<script type="text/javascript">
    function push_file(files)
    { 
    $.ajax
            ({
                type: "post",
                url: "<?php echo base_url(); ?>Appointment/download_files/",
                data: "files=" + files,
               success: function(data)
                {
                   alert('ok' + data);
                }
            });
    }
    </script>

PHP代码和这里我想下载文件在这里和

foreach($results as $row){
    $r_id = $row->id;
    <td><h5><a onclick="push_file(<?php echo $r_id;?>)"> Download </a></hs><t>
    }

控制器Ajax和PHP可以很好地读取文件,但不能下载

public function download_files() {
       //$this->load->view ( 'ajax/download' );
       if($_POST)
    {
    $base = base_url();
    $id = $_POST['files'];
    $query = $this->db->query("select userfile from patient_report_file where        id='".$id."'");
    $result = $query ->row();
    $name = $result->userfile;
    echo $path = $base."Admin/uploads/patient_report/".$name; 
    force_download($path, NULL);
    }
     }

如何下载文件

你试图通过ajax下载一个文件,这是不可能的(至少你做的方式)

现在你有两个选项

选项#1 -把JS留在后面(为什么你在这里甚至需要JS - an)下载后提示是无用的imho)

你的视图应该看起来像

foreach($results as $row)
{
    echo '<td><h5><a href="'.base_url().'/Appointment/download_files/'.$row->id.'/"> Download </a></h5></td>';
}

和控制器

public function download_files($id) 
{
    //$this->load->view ( 'ajax/download' );
    $base = base_url();
    $id = $_POST['files'];
    $query = $this->db->query("select userfile from patient_report_file where        id='".$id."'");
    $result = $query ->row();
    $path = $base."Admin/uploads/patient_report/".$result->userfile; 
    force_download($path, NULL);
}

选项#2 -有点棘手,因为它需要一些适应,我不打算为你写那个代码,而是给你一些学习

的链接

使用jQuery下载文件。Ajax

https://github.com/eligrey/FileSaver.js/

使用ajax请求下载文件


总的来说,我不是在评判你的代码,但你做了一个相当糟糕的工作,以正确使用CI;)

如果你想使用POST方法,这是我的解决方案:

crsf启用:

<script>
function push_file(files)
    { 
    $('<form action="<?php echo site_url('admin/others/test');?>" method="post"><input type="hidden" name="files" value="'+files+'"><input type="hidden" name="csrf_token_name" value="<?php echo $this->input->cookie('csrf_cookie_name');?>"></form>').submit();
    }
    </script>

crsf禁用:

<script>
function push_file(files)
    { 
    $('<form action="<?php echo site_url('admin/others/test');?>" method="post"><input type="hidden" name="files" value="'+files+'"></form>').submit();
    }
    </script>

您必须更改路径控制器。