CSV下载而不是在Nginx上显示Laravel 7



我在生产服务器上下载文件时遇到问题。使用不同的浏览器会得到相同的结果,在测试服务器上成功,在不更改当前页面的情况下作为文件下载。然而,在生产服务器上,它只需打开一个新的选项卡,并在页面上以文本形式显示csv。我只能认为这与服务器(Nginx(有关。我可以更改服务器块以给出正确的行为吗。

Javascript客户端代码

window.open('myfile.csv');

Laravel控制器代码

protected function download(){
$filename=$_GET["filename"];
//return response()->download(public_path()."/downloads".$filename);
$fileContent = file_get_contents($filename);
$response = response($fileContent, 200, [
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="'.$filename.'"',
]);
return $response;
}

响应标头:

测试服务器

Accept-Ranges: bytes
Connection: keep-alive
Content-Length: 318
Content-Type: application/octet-stream
Date: Mon, 27 Apr 2020 16:29:06 GMT
ETag: "5ea70851-13e"
Last-Modified: Mon, 27 Apr 2020 16:29:05 GMT
Server: nginx/1.16.1

生产服务器

Cache-Control: no-cache
Cache-Control: no-cache
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/plain
Date: Mon, 27 Apr 2020 16:32:00 GMT
ETag: W/"5ea70900-13e"
Expires: Mon, 27 Apr 2020 16:31:59 GMT
Last-Modified: Mon, 27 Apr 2020 16:32:00 GMT
Server: nginx/1.8.0
Transfer-Encoding: chunked

我只能控制生产中的虚拟服务器块。为了证实这一点,下面是几篇有用的帖子——代码在测试服务器和所有浏览器上都有效,在生产服务器和所有服务器上都无效。

protected function download() {
$filename = public_path() . "/downloads" . $_GET["filename"];
$fileContent = file_get_contents($filename);
return response($fileContent, 200,
[
'Content-Type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="' . $filename . '"'
]);
}

请尝试以下操作:

function downloadFile(fileName, type="text/plain") {
// Create an invisible A element
const a = document.createElement("a");
a.style.display = "none";
document.body.appendChild(a);
// Set the HREF to a Blob representation of the data to be downloaded
a.href = url;
// Use download attribute to set set desired file name
a.setAttribute("download", fileName);
// Trigger the download by simulating click
a.click();
// Cleanup
document.body.removeChild(a);
}

如果你有任何错误,请告诉我。

希望它能帮助你

谢谢

最新更新