简体   繁体   English

从Ajax调用PHP函数-下载文件

[英]PHP function call from ajax - download file

I am trying to use Ajax & PHP Function for downloading a file. 我正在尝试使用Ajax和PHP函数下载文件。 my goal is to use Ajax for sending variables from Datatable to PHP function. 我的目标是使用Ajax从Datatable向PHP函数发送变量。 and PHP function will search for the file in my storage and download it. PHP函数将在我的存储中搜索文件并下载。

It's not working. 没用 when I using the URL I can download the file. 使用URL时,我可以下载文件。 but when I trigger it with AJAX it's not working. 但是当我用AJAX触发它时,它不起作用。

I want to create a PHP function that will receive file name and generate the download link for an HTML button. 我想创建一个PHP函数,该函数将接收文件名并生成HTML按钮的下载链接。 (which displayed in a data table) (显示在数据表中)

Ajax: 阿贾克斯:

       //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: 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: 路线:

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