我有一个下载文件servlet代码,它将动态地将内容添加到CSV文件中供用户下载。但是,页面的 HTML 代码不会将我想要的内容添加到 CSV 文件中,而是显示在文件中。谁能告诉我是什么导致了这个错误?这是我的控制器代码
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, ggggn";
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 代码复制到文件中,我也意识到它是多余的,我已经将它们注释掉了。这是导致问题的代码。
好吧,如果您只想重新加载当前页面,那么您可以做一个技巧:
您的<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, ggggn";
outputStream.write(outputResult.getBytes());
outputStream.flush();
outputStream.close();
} catch(Exception e) {
//logging
}
}
如果你想使一个在页面加载时隐藏的div可见,那么与其调用location.reload()
你应该调用$('#divId').show()