[英]Can't direct download after creating a CSV file
I've seen a lot of answers of this type of questions but none worked for me. 我已经看到了很多这类问题的答案,但没有一个对我有用。 I've a CSV object which has a createCSV function like this : 我有一个CSV对象,它具有如下的createCSV函数:
public function createCSV($url, $delimiter = ","){
$file = fopen($url, 'w');
foreach ($this->content as $line) {
fputcsv($file, $line, $delimiter);
}
fclose($file);
}
And I want to download it directly from the browser so here is what I do : 而且我想直接从浏览器中下载它,因此我可以这样做:
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
$csv_file->createCSV('php://output');
This part of code is execute with an AJAX call and even if the header is set to text/csv
the download doesn't work but in the response tab I can see the content of my csv. 这部分代码是通过AJAX调用执行的,即使将标头设置为text/csv
,下载也不起作用,但是在“响应”选项卡中,我可以看到csv的内容。 I've tried with different header but none of them worked. 我尝试使用不同的标题,但没有一个起作用。 How can I do to download the CSV ? 如何下载CSV?
EDIT 编辑
The thing is that I don't have a URL for my CSV and I don't want to store the file somewhere, I just want to build the file and download directly with the browser 事实是,我没有CSV的URL,也不想将文件存储在某个地方,我只想构建文件并直接通过浏览器下载
Try this code: 试试这个代码:
$('#exportcsv').click(function(){
var self = this;
$.ajax({
url : '/exportcsv',
method : 'get',
success : function(response)
{
console.log(response);
var csvData = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(response);
$(self).attr({
'download': 'publisher.csv',
'href': csvData,
'target': '_blank'
});
// window.open(uri, 'test.csv');
}
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.