我有一个downloadfile servlet代码,该代码将内容动态添加到csv文件中,以供用户下载。但是,不是将我想要添加的内容添加到csv文件中,而是页面的HTML代码显示在文件中。任何人都可以告诉我是什么导致了此错误?这是我的控制器代码
response.setContentType("text/csv");
response.setHeader("Content-Disposition", "attachment";
filename="\\evaluations.csv\\");
try
{
OutputStream outputStream = response.getOutputStream();
String outputResult = "xxxx, yyyy, zzzz, aaaa, bbbb, ccccc, dddd, eeee, ffff, gggg\n";
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
} catch(Exception e) {
status = "Error exporting file, please try again later";
System.out.println(e.toString());
}
//request.setAttribute("status",status);
//dispatcher = request.getRequestDispatcher("/viewEvaluations.jsp");
//dispatcher.forward(request, response);
编辑:
删除转发请求实际上阻止了HTML代码被复制到文件中,并且我也意识到了它的冗余,我已经将它们注释掉了。这是导致问题的代码。
答案 0 :(得分:1)
好吧,如果您只是想重新加载当前页面,那么您可以做个技巧:
您的<a>
标签应如下所示:
<a href="javascript:void(0)" id="test">Click Here</a>
在Jquery中:
$('#test').click(function()
{
location.href='download'; //your download request mapping
setTimeout(function(){location.reload()},2000); //this will reload the current page after 2 seconds.
});
您的控制器代码为:
@RequestMapping(value = "download", method = RequestMethod.GET)
public void download(Locale locale, Model model,HttpServletRequest request,HttpServletResponse response,HttpSession session) {
response.setContentType("text/csv");
response.setHeader("Content-disposition", "attachment; filename=evaluations.csv");
try
{
OutputStream outputStream = response.getOutputStream();
String outputResult = "xxxx, yyyy, zzzz, aaaa, bbbb, ccccc, dddd, eeee, ffff, gggg\n";
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
} catch(Exception e) {
//logging
}
}
如果要使可见的div在页面加载时隐藏,则应调用location.reload()
$('#divId').show()