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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17706819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:44:33  来源:igfitidea点击:

How to return a text file with Spring MVC?

javaspringspring-mvc

提问by Mythul

@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";
}

The string is generated inside the Controller. What I want is to send back to the user a Window where he can save a file which contains the myString.

字符串在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.");
    }
});

It clearly doesn't work in this current state and I am stuck at the moment.

它显然在当前状态下不起作用,我现在被卡住了。

回答by Farid

here is a sample:

这是一个示例:

@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();
}

PS: don't forget to put some random stuff in your url (as parameter for example) to ensure your browser does not cache the text file.

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

回答by Juned Ahsan

To return a file you need to use the MediaType.APPLICATION_OCTET_STREAMas the response type.

要返回文件,您需要将MediaType.APPLICATION_OCTET_STREAM用作响应类型。

回答by dwjohnston

I recommend using filesaver.js.

我建议使用filesaver.js

Then your solution will look like:

那么您的解决方案将如下所示:

var text = JSON.stringify(createJSON());  
var blob = new Blob([text], {type: "text/plain; charset=utf-8"});                           
saveAs(blob, "myfile.txt");