英文:
Generating and Downloading CSV file using apache common csv
问题
我已经使用以下方法从数据库生成并下载了一个CSV文件:
String path = request.getServletContext().getRealPath("assets/file.csv");
try {
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get(path));
CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, CSVFormat.DEFAULT.withHeader("Name"));
for (String name : names) {
csvPrinter.printRecord(name);
}
csvPrinter.flush();
csvPrinter.close();
jsonObject.addProperty("result", "succ");
} catch (Exception e) {
e.printStackTrace();
}
我使用ajax调用了这个方法。我的jsp文件中调用了这个方法:
<% String file = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/assets/file.csv";
%>
<button id="download" type="button">Download</button>
<a id="file" target="_blank" href="<%= file %>" style="display: none"></a>
<script type="text/javascript">
$(function(){
$('#download').on('click', function(){
$.ajax({
//ajax代码
success: function(response){
console.log(response);
var resp = JSON.parse(response);
if(resp.result == "succ"){
document.getElementById("file").click();
}
},
error: function(xhr, err){
}
});
});
});
</script>
但问题是,当我第一次尝试下载文件时,它返回404页面,当我再次运行时,它返回最后生成的文件。
经过调试,我发现文件生成较晚。
英文:
I have used the below method to generate and download a csv file from database
String path= request.getServletContext().getRealPath("assets/file.csv");
try{
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get(path));
CSVPrinter csvPrinter = new CSVPrinter(bufferedWriter, CSVFormat.DEFAULT.withHeader("Name"));
for(String name: names){
csvPrinter.printRecord(name);
}
csvPrinter.flush();
csvPrinter.close();
jsonObject.addProperty("result", "succ");
}catch (Exception e) {
e.printStackTrace();
}
And i'm using ajax to call this method.
My jsp file where calling this method
<% String file= request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
+ request.getContextPath() + "/assets/file.csv";
%>
<button id="download" type="button">Download</button>
<a id="file" target="_blank" href="<%= file%>" style="display: none"></a>
<script type="text/javascript">
$(function(){
$('#download').on('click', function(){
$.ajax({
//ajax code
success: function(response){
console.log(response);
var resp = JSON.parse(response);
if(resp.result == "succ"){
document.getElementById("file").click();
}
},
error: function(xhr, err){
}
});
});
But the issue is when I'm trying to download the file for first time it is returning 404 page and when i'm running again it is returning the last generated file.
After debugging I found that the file is getting generated late.
专注分享java语言的经验与见解,让所有开发者获益!
评论