有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我使用了类似于下面的代码,将zip文件作为SpringMVC请求的附件返回。整个程序运行得很好,我可以下载一个名为hello的文件。当我向localhost/app/getZip发出请求时

我的问题是,如何提示用户输入文件名。目前在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,我希望用户提供一个文件名,而不是在头中传递一个


共 (1) 个答案

  1. # 1 楼答案

    使用方法到请求方法。获取
    URL: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();
        }
    }