现在可以从Spring控制器下载文件,但没有对话框,文件直接保存到浏览器的下载文件夹中。我想要一个文件对话框,询问用户要保存在哪个文件夹中。如何做到这一点?代码是
@RequestMapping(value = "/export", method = RequestMethod.GET)
@ResponseBody
public ModelAndView export(HttpServletResponse response) {
try {
String str = "sep=tn"; // 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;
}
您必须记住,您的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应用程序发出浏览器提示。