我无法下载文件强制下载无法正常工作如何修复和下载文件

时间:2016-11-07 08:01:10

标签: javascript php ajax html5 codeigniter

我无法下载文件。我正在尝试通过Ajax从服务器下载文件。我在Ajax数据中获得了成功响应,并在响应中提交文件,但文件未下载我所做的以及如何解决此问题。文件读取成功,并且切断路径也正常。请帮我。

当我调用function并获得响应时,这个是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);
    }

     }

如何下​​载文件。

2 个答案:

答案 0 :(得分:0)

您尝试通过ajax下载文件,这是不可能的(至少按照您的方式)

现在你有两个选择

  

选项#1 - 让JS落后(为什么你甚至需要JS - 一个   下载后的警报是无用的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 - 有点棘手,因为它需要一些适应性,我不会为你编写代码,而是我给你一些学习链接

Download a file by jQuery.Ajax

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

download file using an ajax request

总的来说,我不是在判断您的代码,但为了正确使用CI,您做得非常糟糕;)

答案 1 :(得分:0)

如果你想使用方法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>

你必须改变路径控制器。