這個問題在這里已經有了答案: 通過 jQuery.Ajax 下載檔案 (26 答案) 1 小時前關閉。
我需要在 ajax 呼叫中下載 CSV 檔案。
我可以在 Laravel 控制器中訪問我的 ajax 請求。我也可以在我的 ajax 呼叫的成功函式中獲得檔案內容的回應。但是檔案沒有被下載。
laravel 控制器代碼:
public function export($request)
{
$details = $this->myService->getData($request);
$csv_data = new Collection();
if ($details->count() === 0) {
return $csv_data;
}
foreach ($details as $detail) {
$collection = collect([
'id' => $detail->id,
]);
$csv_data->push($collection);
}
$csv_file_name = abc.csv;
$csv_headers = 'id'];
$csv_column_names = [ 'id'];
$callback = function () use ($csv_data, $csv_file_name, $csv_headers, $csv_column_names) {
$stream = fopen('php://output', 'w');
stream_filter_prepend($stream, 'convert.iconv.utf-8/cp932//TRANSLIT');
$header = '"';
$header .= implode('","', $csv_headers);
$header .= '"';
$header .= "\r\n";
fwrite($stream, $header);
foreach ($csv_data as $row) {
$arr_data = [];
foreach ($csv_column_names as $column_name) {
array_push($arr_data, $row->get($column_name));
}
$data = '"';
$data .= implode('","', $arr_data);
$data .= '"';
$data .= "\r\n";
fwrite($stream, $data);
}
fclose($stream);
};
$filename = $csv_file_name;
$header = [
'Content-Type' => 'application/octet-stream',
];
return response()->streamDownload($callback, $filename, $header);
}
我的ajax呼叫
$('#csv-file').on('click',function(e){
e.preventDefault();
let id = $("select[name='user_id']").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/user/csv",
type:"POST",
data:{
id:id,
},
success:function(response){
$( "#error" ).remove();
console.log(response);
},
error: function(response) {
$( "#error" ).remove();
let errorView =
`<div id="error">
<h6>Error:</h6>
<ul >
<li>` response.responseJSON.message `</li>
</ul>
</div>`;
$("#error-id").prepend(errorView);
},
});
});
在我的 ajax 呼叫的成功函式中,我可以控制臺日志并獲取檔案內容。但我需要下載未下載的檔案。
提前致謝。
uj5u.com熱心網友回復:
將此添加到您的 ajax 引數中:
xhrFields: {
responseType: "blob",
}
現在,在成功函式中,添加:
let a = document.createElement("a")
a.href = URL.createObjectURL(response)
a.download = response.filename
a.style.display = "none"
document.body.appendChild(a)
a.click()
這應該有效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/520024.html
