gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:42:59 25 4
gpt4 key购买 nike

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

下面是我的代码:

<button type="button" request_id="'.$data->id.'" class="btn btn-success download_request_btn" > Download </button>';

Controller :

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

Ajax :

$(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) {

}
});
});

最佳答案

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

$(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();
}
});
});

关于javascript - 单击按钮无法在 laravel ajax 中下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64747187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com