从ajax请求下载laravel pdf文件(laravel 5)

mos*_*toh 6 javascript pdf ajax download laravel

我的html代码是这样的:

<a href="javascript:;" onclick="showAjaxPdf('{{ $row->file_path }}');"><i class="fa fa-file-pdf-o"></i></a>
Run Code Online (Sandbox Code Playgroud)

我的JavaScript代码是这样的:

function showAjaxPdf(file_path)
        {
            var file_path = file_path.replace(/\\/g,"/");
            //example : file_path = assets/images/myfile.pdf
            $.ajax({
                type: "POST",
                data: 'file_path=' + file_path,
                url: "news/test",
                success: function(response)
                {
                    $('#test').html(response);

                }
            });
        }
Run Code Online (Sandbox Code Playgroud)

我在控制器中的功能测试:

public function postTest(Request $request)
    {
$file_path = $request->input('file_path');  
        return response()->download($file_path);       
    }
Run Code Online (Sandbox Code Playgroud)

当我单击pdf图标时,没有响应。

我希望当单击pdf图标时显示如下:

在此处输入图片说明

单击pdf图标时,图像如何显示?

谢谢

HIt*_*ank 0

为此,您需要使用响应对象设置标头。请看下面的代码。

    $headers = array(
                  'Content-Type'=> 'application/pdf'
                );
$file_path = $request->input('file_path');  
 //TODO: you have to split the file name from url 
 return Response::download($file_path, '<filename>', $headers);
Run Code Online (Sandbox Code Playgroud)

我希望这段代码能帮助你