来自ajax的PHP函数调用 - 下载文件

时间:2018-03-04 09:34:09

标签: php ajax laravel downloadfile

我正在尝试使用Ajax& PHP用于下载文件的函数。 我的目标是使用Ajax将变量从Datatable发送到PHP函数。 和PHP函数将搜索我的存储中的文件并下载它。

它不起作用。当我使用URL我可以下载文件。但是当我用AJAX触发它时,它不起作用。

我想创建一个PHP函数,它将接收文件名并生成HTML按钮的下载链接。 (显示在数据表中)

的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:

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

0 个答案:

没有答案