java - 如何从 Spring Controller 创建文件保存对话框?

标签 java spring file download

现在可以从Spring Controller 下载文件,但没有对话框,文件直接保存到浏览器的下载文件夹中。我想要一个文件对话框,询问用户要保存在哪个文件夹中。该怎么做?代码是

@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;
}

最佳答案

您必须记住,您的 Spring Web 应用程序应该是一个兼容 HTTP 的应用程序。 HTTP 是一种请求-响应协议(protocol)。客户端发送请求,服务器发送响应。

在您的情况下,响应将如下所示

HTTP/1.1 200 OK 
Content-Disposition: attachment; filename=Users-export.csv
Content-Type: application/xls
Content-Length: XYZ

<bytes goes here>

您的客户端(即浏览器)将收到此消息并对其进行任何选择。您应该检查浏览器设置并启用另存为...提示。

<小时/>

无法强制 Web 应用程序显示浏览器提示。

关于java - 如何从 Spring Controller 创建文件保存对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20642217/

相关文章:

c - 从C中的文件中读取特定字段

java - 如何在Android中处理后退按钮而无需再次连接网络

来自 URL : "FileNotFoundException" 的带有 FileSystemResource 的 Java 邮件附件

java - 在配置中设置批量大小

java - bean 的空属性会被插入到 MongoDB 中吗?

java - AOP @Before 方法未调用

spring - 如何修复 "Invalid remember-me token (Series/token) mismatch"错误?

php - 如何按内容存储和搜索 mp3

c - 打开时出现段错误

java - 如何通过 Play! 中的请求启动后台线程!框架?