如何使用Spring MVC返回文本文件?

Myt*_*hul 3 java spring spring-mvc

@RequestMapping( method = RequestMethod.POST, value = DataController.RESOURCE_PATH + "/file", headers = "content-type=application/json" )
@ResponseBody
public void export( @RequestBody JSONObject json, HttpServletResponse response ) throws IOException
{
    String myString = "Hello";
}
Run Code Online (Sandbox Code Playgroud)

字符串是在里面生成的Controller.我想要的是向用户发送一个窗口,在那里他可以保存一个包含该文件的文件myString.

$.ajax({
    type: "POST",
    url: url,
    data: JSON.stringify(createJSON()),
    contentType: "application/json",
    success: function(response)
    {
        console.log("Exported JSON: " + JSON.stringify(createJSON()));
        console.log(response);
    },
    error: function()
    {
        console.log(arguments);
        alert("Export process failed.");
    }
});
Run Code Online (Sandbox Code Playgroud)

它显然在当前状态下不起作用,此刻我陷入困境.

Far*_*rid 13

这是一个示例:

@RequestMapping( method = RequestMethod.POST, 
    value = DataController.RESOURCE_PATH + "/file", 
    headers = "content-type=application/json" )
public void export( @RequestBody JSONObject json, HttpServletResponse response ) 
    throws IOException {
    String myString = "Hello";
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition","attachment;filename=myFile.txt");
    ServletOutputStream out = response.getOutputStream();
    out.println(myString);
    out.flush();
    out.close();
}
Run Code Online (Sandbox Code Playgroud)

PS:不要忘记在你的网址中添加一些随机内容(例如参数),以确保浏览器不会缓存文本文件.