单击按钮时无法在 laravel ajax 中下载文件

jan*_*dhi 2 javascript jquery laravel

当我尝试使用 laravel ajax 中的下载按钮下载文件时,它无法正常工作,并且我无法下载文件。

下面是我的代码:

<button type="button" request_id="'.$data->id.'" class="btn btn-success download_request_btn" > Download </button>';
Run Code Online (Sandbox Code Playgroud)

控制器:

public function downloadReport(Request $request)
    {
        $request_id = $request->request_id;
        $downloadReport = Upload::where('id', $request_id)->first();
        $upload_report = $downloadReport->upload_report;
        $headers = array(
            'Content-Type: application/pdf',
            'Content-Type: application/docx',
          );
        $url= url('storage/documents/request/'. $upload_report);
        return response()->download($url);
    }
Run Code Online (Sandbox Code Playgroud)

阿贾克斯:

$(document).on('click', '.download_request_btn', function(){
            var request_id = $(this).attr('request_id');
           console.log(request_id);
           var formData = new FormData();
            formData.append('request_id',request_id);
            jQuery.ajax({
                type: "post",
                url: site_url+"/DownloadAjax",
                data: formData,
                contentType:false,
                processData:false,
                success: function (res) {

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

jer*_*edy 5

只是为了伪代码相信您的数据会根据需要返回,我认为您需要在成功回调中触发下载,并使用以下内容的变体(可能需要根据您的需要进行调整):

$(document).on('click', '.download_request_btn', function(){
    var request_id = $(this).attr('request_id');
    console.log(request_id);
    var formData = new FormData();
    formData.append('request_id',request_id);
    jQuery.ajax({
        type: "post",
        url: site_url+"/DownloadAjax",
        data: formData,
        contentType:false,
        processData:false,
        success: function (res) {
            const data = res;
            const link = document.createElement('a');
            link.setAttribute('href', data);
            link.setAttribute('download', 'yourfilename.extensionType'); // Need to modify filename ...
            link.click();
        }
    });
});
Run Code Online (Sandbox Code Playgroud)