我正在尝试从浏览器导出csv文件。所以流程是下一个。当我在GUI上单击按钮导出时,它应该在后端创建csv文件并在浏览器中显示给我(如下载)。但这不会发生。当我点击按钮它从后端调用我的方法它创建csv文件并将其存储到文件夹但它没有在浏览器中显示该文件。这是我的代码:public void export(HttpServletResponse response) throws IOException {
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter("exported.csv");
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
// create a List which contains String array
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] { "Name", "Class", "Marks" });
data.add(new String[] { "Aman", "10", "620" });
data.add(new String[] { "Suraj", "10", "630" });
writer.writeAll(data);
// closing writer connection
writer.close();
response.setContentType("application/ms-excel"); // or you can use text/csv
response.setHeader("Content-Disposition", "attachment; filename=exported.csv");
}
catch (IOException e) {
e.printStackTrace();
} }编辑:角部分:.service('ExportService', function($http) {
this.export = function() {
return $http.post('/data/export', { responseType: 'application/octet-stream' });
};
})$scope.export = function() {
ExportService.export()
.success(function(data, status, headers, config) {
var blob = new Blob([data], { type: 'application/octet-stream' });
saveAs(blob, 'Exported - exported.csv');
$.growl({ message: '<br>successfully exported', title: '<b>SUCCESS</b>' }, { type: 'success' });
})
.error(function(data, status, headers, config) {
$.growl({ message: '<br>Exporting failed', title: '<b>ERROR</b>' }, { type: 'danger' });
});
}有谁知道可能是什么问题?
2 回答
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
您永远不会将文件发送到客户端。您甚至不必先将数据写入服务器上的文件。只需使用OutputStreamWriter:
public void export(HttpServletResponse response) throws IOException {
try (CSVWriter writer = new CSVWriter(new OutputStreamWriter(response.getOutputStream(), StandardCharsets.UTF_8)) {
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment; filename=exported.csv");
List<String[]> data = new ArrayList<String[]>();
data.add(new String[] { "Name", "Class", "Marks" });
data.add(new String[] { "Aman", "10", "620" });
data.add(new String[] { "Suraj", "10", "630" });
writer.writeAll(data);
}}顺便说一下:我用try块替换了try-with-resources块。这样close(),即使存在异常,也要确保始终调用writer 的方法。此外,没有必要在这个地方捕获异常,因为该方法的调用者必须处理IOExceptions。
隔江千里
TA贡献1906条经验 获得超10个赞
您正在将数据写入exported.csv服务器上本地调用的文件。此文件不会发送到客户端。
您应该将文件的内容写入response.getOutputStream()。
添加回答
举报
0/150
提交
取消
