通过javascript中的API调用下载文件

I'm trying different things to download a file via my API which is called by javascript (axios). I can see that my response from the api is Resource id #19 and that it contains the correct information but how do I now download it?

PHP code

$filename = "Export file";
$delimiter = "\t";
$output = fopen('php://output', 'w');
fwrite($output, "sep=\t" . PHP_EOL);

// ... put stuf in document

fclose($output);

header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename=' . $filename . '.csv');
header('Content-Type: text/csv; charset=utf-8');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo $output; // also tried readfile($output) but it triggers an error that it needs a valid path

php://output is a write-only stream that allows you to write to the output buffer mechanism in the same way as print and echo. You can not read back from this stream.

I think you want to use php://input instead to read the response body.

Finally found that it is not possible to download via ajax request. Just open a new window with the url and it downloads fine.

Example (client side)

var win = window.open(`${apiPath}export`, '_blank');
win.focus();