Java使用ajax创建和下载文件不起作用

时间:2019-02-28 10:11:14

标签: java ajax file spring-mvc

我正在尝试生成一些报告,并使用我的csv file作为Java Spring MVC Web Application下载。我在浏览器上显示了一个数据列表,并带有选择多个行的选项,我正在尝试创建一个具有选定行的csv文件并下载csv文件。我的控制器方法如下:

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对象具有必需的值。我正在使用以下脚本来调用控制器方法:

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

运行代码时没有出现任何错误,但没有看到任何下载选项。

0 个答案:

没有答案