簡體   English   中英

我無法下載文件強制下載不起作用如何修復和下載文件

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

我無法下載文件。我正在嘗試通過Ajax從服務器下載文件。 我在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);
    }

     }

如何下載文件。

您嘗試通過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-有點棘手,因為它需要一些適應性,我不會為您編寫該代碼,但我為您提供了一些學習鏈接

通過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>

您必須更改路徑控制器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM