如何使用Spring控制器强制下载文件?

如何使用Spring控制器强制下载文件?,spring,browser,download,Spring,Browser,Download,我有一个字符串控制器来下载xml文件,但下载窗口每次都是打开的 这是我的控制器的代码: @RequestMapping(value = "/export", method = RequestMethod.POST) @ResponseBody public void export(HttpServletRequest request, HttpServletResponse response) throws JsonGenerationException, JsonMap

我有一个字符串控制器来下载xml文件,但下载窗口每次都是打开的

这是我的控制器的代码:

    @RequestMapping(value = "/export", method = RequestMethod.POST)
@ResponseBody
public void export(HttpServletRequest request, HttpServletResponse response) throws JsonGenerationException,
        JsonMappingException, IOException, DatatypeConfigurationException {
    byte[] bytes  = service.exportXML(getUsername());
    String xmlFileName = "filename.xml";
     response.setContentType("application/force-download");
     response.setHeader("Content-Length", String.valueOf(bytes.length));
     response.setHeader("Content-Disposition", "attachment; filename="+xmlFileName);

     response.getOutputStream().write(bytes);
}

我能做些什么来防止浏览器不打开下载窗口并立即保存文件?

从服务器端不可能。由于安全原因,如果在浏览器中指定,浏览器将不允许自动下载文件

例如,如果要在浏览器中自动下载并打开docx文件类型。然后检查此链接

希望您理解此处的限制。

尝试添加以下内容:

response.setHeader("Content-Transfer-Encoding", "binary");

我之前试过直接打开的txt文件。它们被保存而不是打开。

这真的会改变浏览器的行为以自动保存文件吗?它不是依赖于浏览器和用户偏好吗?