【发布时间】:2012-08-23 11:35:15
【问题描述】:
编辑
据我所知(来自 nico_ekito 的 cmets),无法使用 ajax 调用来下载文件。解决方案是创建一个隐藏的<iframe> 来下载文件,描述为here。
问题: 浏览器不显示下载对话框。任何浏览器 - ff、opera、chrome、safari 等。
我阅读了关于服务文件的docs,找到了this question,并在此基础上写道:
Controller.response().setContentType("text/csv");
Controller.response().setHeader("Content-Disposition", "attachment;filename=public/export/filename.csv");
Controller.response().setHeader("Cache-control", "private");
return ok(CSV.export(data, filename));
CSV 是一个类:
public class CSV{
public static File export(Map<String, String> data, String filename){
String csv = data.get("data[saveMe]");
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("public/export/" + filename), "UTF-8"));
bw.write(csv);
bw.newLine();
bw.flush();
bw.close();
}catch(UnsupportedEncodingException e){}
catch(FileNotFoundException e){}
catch(IOException e){}
File downloadMe = new File("public/export/" + filename);
return downloadMe;
}
}
在客户端,我使用dojo 发送POST 请求(我也尝试使用GET,结果相同):
xhr.post({
url: '/exportData/',
content: {
saveMe: str
}
}).then(function(response){
//do sth
});
响应标头如下所示:
Cache-Control private
Content-Disposition attachment;filename=public/export/filename.csv
Content-Type text/csv
Transfer-Encoding chunked
POST firebug 中的选项卡以正确的 csv 格式显示正确的数据。要使用 csv 样式格式化数据,我使用 dojox/grid/enhanced/plugins/exporter/CSVWriter
【问题讨论】:
-
您是否尝试过使用 GET 请求而不是 POST ?
-
感谢您的输入,但
GET也不起作用 -
你为什么使用 Ajax 而不是通过 HTML 链接进行简单的 GET 操作?
-
@h4b0 如果你播放 url localhost:9000/exportData/?saveMe=test ,你的浏览器里有东西吗?
-
@Davz 工作正常,浏览器窗口中没有显示任何内容,但我可以看到下载对话框
标签: csv download playframework-2.0