现在可以从Spring控制器下载该文件,但没有对话框,文件直接保存到浏览器的下载文件夹中。我想要一个文件对话框,询问用户要保存的文件夹。如何完成?代码是
@RequestMapping(value = "/export", method = RequestMethod.GET)
@ResponseBody
public ModelAndView export(HttpServletResponse response) {
try {
String str = "sep=\t\n"; // tells excel what the delimiter character should be
Iterator<Individual> iterator = customerAccountService.getAllIndividuals().iterator();
while(iterator.hasNext()){
Individual individual = iterator.next();
str = str + individual.getId() + "\t" +individual.getIndividualName().getName() + "\t" + individual.getAddress().getStreetName() + "\n";
}
InputStream is = new ByteArrayInputStream(str.getBytes());
IOUtils.copy(is, response.getOutputStream());
response.setContentType("application/xls");
response.setHeader("Content-Disposition","attachment; filename=Users-export.csv");
response.flushBuffer();
} catch (IOException ex) {
//logger.info("Error writing file to output stream. Filename was '" + fileName + "'");
throw new RuntimeException("IOError writing file to output stream");
}
ModelAndView modelAndView = new ModelAndView(ViewName.MENU);
modelAndView.addObject(ObjectName.ADD_FORM, new LoginForm());
return modelAndView;
}
答案 0 :(得分:1)
您必须记住,您的Spring Web应用程序应该是一个HTTP兼容的应用程序。 HTTP是请求 - 响应协议。客户端发送请求,服务器发送响应。
在您的情况下,响应将如下所示
HTTP/1.1 200 OK
Content-Disposition: attachment; filename=Users-export.csv
Content-Type: application/xls
Content-Length: XYZ
<bytes goes here>
您的客户端(浏览器)将收到此消息并执行其选择的操作。您应该检查浏览器设置并启用Save As...
提示。
无法从Web应用程序强制显示浏览器提示。