在我的 web 应用程序中,我希望用户下载 csv 文件作为对 POST ajax 请求的响应。响应已正确发送,看起来不错,但在 ajax.success() 没有任何反应。
我不想在服务器上永久写入文件,所以我直接在 PrintWriter 中写入,我读过这应该可以工作。
这是 servlet 的代码:
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
BufferedReader reader = request.getReader();
myData data = mapper.readValue(reader, myData.class);
List<City> cities = data.getCities();
String filename = domain+".csv";
response.setContentType("application/csv");
response.setHeader("content-disposition","filename="+filename);
PrintWriter out = response.getWriter();
/*writes csv rows to out stream*/
for (int i = 0; i <= 50; i++) {
String nome = cities.get(i).getName();
List<FBHit> results = allQueries.get(nome).get();
for (FBHit hit : results) {
hit.writeToCSV(out, nome);
}
}
out.close();
}
这是异步请求的代码:
$.ajax({
url: "/socialpa-2/batchQueryServlet",
contentType: 'application/json',
data: json,
Accept: "text/csv",
success: function(data, textStatus, jqXHR) {
alert(data);
},
type: "POST"
});
当请求返回时,文件内容会显示在警报中,但不会触发下载。如果我删除警报,也不会发生任何事情。我怀疑这个错误要么是错误的接受值,要么是使用 printwriter。
这是 CSV 文件的示例,对我来说看起来不错
"Alassio","http://facebook.com/-1089066187","Città di Alassio",2644
"Albenga","http://facebook.com/-915266586","Comune di Albenga",100
"Albisola Superiore","http://facebook.com/2031157506","Città di Albisola Superiore",536
"Albissola Marina","http://facebook.com/80387060","Comune di Albissola Marina",597
"Bardineto","http://facebook.com/-317945148","Comune di Bardineto",360
"Bergeggi","http://facebook.com/92600835","Comune di Bergeggi",1214
"Cairo Montenotte","http://facebook.com/1413890265","Città di Cairo Montenotte",206
我应该坚持使用java(因为我不是服务器的所有者),如果可能的话,我宁愿不在服务器上写文件。