I am trying to generate some reports and download as csv file
using my Java Spring MVC Web Application
. I have a list of data displayed on the browser with option to select multiple rows and the I am trying to create a csv file with selected rows and download the csv file. My controller method is as follows:
public String downloadBusinessAsFile(@ModelAttribute("ids") String selectedIds, HttpServletRequest request, HttpServletResponse response, ModelMap model)
{
String fileName = new SimpleDateFormat("yyyyMMddHHmmss'.csv'").format(new Date());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename="+fileName);
try
{
Map<String, Obj> sessionBusinesses = (Map<String, Obj>) httpSession.getAttribute("objMap");
ServletOutputStream out = response.getOutputStream();
StringBuffer sb = reportService.writeBusinessesToCSV(selectedIds, sessionData);
InputStream in =
new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(in.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();
httpSession.invalidate();
}
catch (Exception e)
{
e.printStackTrace();
}
return "success";
}
StringBuffer
object returned has the required value. I am using the following scripts to call the controller method:
$(document).on('click', '#add-biz', function(){
var selectedRow = '';
for (var i = 0; i< $('#datTable tbody tr.selected').length; i++)
{
if (i <= 0)
{
selectedRow+=$('#datTable tbody tr.selected')[i].id;
}
else
{
selectedRow+=','+$('#datTable tbody tr.selected')[i].id;
}
}
var url = $("#addUrl").val();
$.ajax(
{
url : url,
type: "GET",
data : {ids: selectedRow},
dataType : "html",
success:function(htmlData)
{
if(htmlData == "error")
{
$('#btn-div').html("<p>An error occurred</p>")
}
else
{
$("#successAlert").show();
}
$('#divLoading').hide();
},
error: function( xhr, status, errorThrown ) {
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
});
});
I do not get any error while running the code but do not see any download option.