前一段时间工作中,遇到一个在web应用中生成文本文件并下载的问题,一开始把问题想复杂化了(想了很多如何生成临时文件和文件传输的问题),后来发现其实解决方法很简单,此处总结一下,就几行代码(伪代码):


response.contentType = "text/plain";
response.setHeader("Content-Disposition","attachment; filename=export.txt");
//build filecontent string ...
ByteArrayOutputStream baos = response.out;
baos.write(filecontent.toString().getBytes());
baos.close();


其实就是利用设置http响应头内contentType和Content-Disposition的值,返回给浏览器时会自动下载到本地,简单吧。

希望对大家有所帮助。