java - 保存时 HttpServletResponse 提示输入文件名

标签 java spring-mvc servlets

我使用类似于下面的代码来返回一个 zip 文件作为 SpringMVC 请求的附件。整个事情运行得很好,当我向 localhost/app/getZip 发出请求时,我能够下载一个名为 hello.zip 的文件。

我的问题是,如何提示用户输入文件名。目前,在 FireFox25.0 上,它会自动假定名称为“hello.zip”,而无需在“打开”或“保存”选项上更改文件名。

    @RequestMapping("getZip")
    public void getZip(HttpServletResponse response)
    {
        OutputStream ouputStream;
        try {
            String content = "hello World";
            String archive_name = "hello.zip";
            ouputStream = response.getOutputStream();
            ZipOutputStream out = new ZipOutputStream(ouputStream);
            out.putNextEntry(new ZipEntry(“filename”));
            out.write(content);
            response.setContentType("application/zip");
            response.addHeader("Content-Disposition", "attachment; filename="+ archive_name);
            out.finish();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

TL;DR:使用 HttpServletResponse 我希望用户提供文件名,而不是在 header 中传递文件名。

最佳答案

带有RequestMethod.GET方法
网址:http://localhost/app/getZip?filename=hello.zip

@RequestMapping(value = "getZip/{filename}", method = RequestMethod.GET)
public void getZip(HttpServletResponse response, @PathVariable String filename)
{
    OutputStream ouputStream;
    try {
        String content = "hello World";
        String archive_name = "hello.zip";
        ouputStream = response.getOutputStream();
        ZipOutputStream out = new ZipOutputStream(ouputStream);
        out.putNextEntry(new ZipEntry("filename"));
        out.write(content);
        response.setContentType("application/zip");
        response.addHeader("Content-Disposition", "attachment; filename="+ archive_name);
        out.finish();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

关于java - 保存时 HttpServletResponse 提示输入文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20881144/

相关文章:

java - 从安卓播放列表中获取下一首/上一首歌曲

java - 使用 Spring MVC 保存文件

java - 将servlet发送回Java页面或返回html页面

java - Apache Struts 和 Java EE 之间的区别?

java - ArrayAdapter刷新数据

Java-8 - 从 Optional.of(String) 的开头替换 "?"字符

java - JPA Criteria API - 如何添加 JOIN 子句(尽可能一般的句子)

java - 实体、服务类和命令对象的最佳实践问题

java - thymeleaf :switch with th:each

java - 从命令行编译类时出错