这与我的回答 here 有关,为 csv 和您的代码编辑。
显然这是一个有时会发生的Safari 12 bug。 target = "_self" 没有修复它,它属于 different regression bug。
在修复错误之前,丑陋的解决方法是:
- 将 blob 发送到远程保存文件的服务器。
- 下载远程文件。
Javascript 代码
async createDownloadElementAndClick(csvFile, fileName) {
let options = {
method:"POST",
body:csvFile
};
await fetch(`https://example.com/upload.php`, options);
window.open(`https://example.com/download.php?${fileName}`, "_self");
}
所以从你原来的代码,改成:
var convertedCsv = "name,Designation,City,State,email,mobileNumber,roleType,signUpDate+\n" +
"A,B,C,D,F,G,I,J \n" +
"A1,B1,C1,D1,F1,G1,I1,J1";
var data = new Blob([convertedCsv], {type: 'text/csv'});
var csvFile = window.URL.createObjectURL(data);
//just add this to replace window.open()
createDownloadElementAndClick(csvFile, "myFile.csv")
PHP 代码
在upload.php中:
<?php
// add any authentication code as necessary here
// gets entire POST body
$data = file_get_contents('php://input');
$filename = "temp/download.csv";
// write the data out to the file
$fp = fopen($filename, 'wb');
fwrite($fp, $data);
fclose($fp);
?>
在download.php中:
<?php
ob_start();
$file = $_SERVER["QUERY_STRING"];
// This is the line that tells Safari to download the file instead of opening it
header("Content-disposition: attachment; filename=$file");
header("Content-type: text/csv", false);
readfile("temp/download.csv");
ob_flush();
// This deletes the file so there is little chance of contaminating the next call
unlink("temp/download.csv");
?>