繁体   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