2016-11-07 112 views
0

我无法下载file.I试图通过Ajax从服务器下载文件。我在Ajax数据中获得了成功响应,并且还收到了文件,但是文件没有下载我所做的以及如何解决此问题。该文件读取成功,并且切断路径正确。请帮帮我。我无法下载文件强制下载无法正常工作如何修复和下载文件

这一个是Java脚本时,我调用函数,并得到响应扔阿贾克斯

<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); 
    } 

    } 

怎么样ca我下载文件。

回答

0

您尝试通过Ajax这是不可能的(至少你的方式做到了)

现在你有两个选择

选项#下载文件1 - 离开JS背后(为什么你甚至不需要JS在这里 - 一个 警报后下载也没用恕我直言)

您认为应该像

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一个非常糟糕的工作;)

+0

选项#1是bettar解决方案,但仍然无法下载文件空白页面显示。 –

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> 

您必须更改路径控制器。