我使用类似于下面的代码来返回一个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/