簡體   English   中英

從Ajax調用PHP函數-下載文件

[英]PHP function call from ajax - download file

我正在嘗試使用Ajax和PHP函數下載文件。 我的目標是使用Ajax從Datatable向PHP函數發送變量。 PHP函數將在我的存儲中搜索文件並下載。

沒用 使用URL時,我可以下載文件。 但是當我用AJAX觸發它時,它不起作用。

我想創建一個PHP函數,該函數將接收文件名並生成HTML按鈕的下載鏈接。 (顯示在數據表中)

阿賈克斯:

       //download button
    $('#files').on('click', 'button#download',function (ref) {
        var data = table.row($(this).parents('tr')).data();
        var file_name=data.filename;
        ref.preventDefault();
      //  alert(data.filename);
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
        $.ajax({
            type: 'POST',
            datatype:'binary',
            url: "/download?"+data.filename,
            success: function(result){
                console.log(result);
            }
        });
    });

PHP:

    public function getDownload(){
    $tmpfile='1520001503b1.png';
   $sd= DB::table('files')
        ->where('filename',$tmpfile)
        ->get();


    $myFile = public_path("uploads/1520001503b1.png");
    $headers = ['Content-Type: application/png'];
    $newName = 'bla'.time().'.png';


    return response()->download($myFile, $newName, $headers);

}

路線:

Route::match(['get', 'post'], '/download','FilesController@getDownload');

據我所知,您不能從直接的ajax請求中下載文件,而是可以將動態下載URL返回到ajax響應,並且僅觸發瀏覽器位置更改,如下所示。

location.href = 'download.php';

暫無
暫無

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

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