CSV文件未在Spring MVC中下载

时间:2015-11-18 07:06:53

标签: jquery ajax spring csv

我正在尝试在我的代码中下载CSV文件,我有以下控制器代码

@RequestMapping(value = "/navdb/group/{groupIdent}/edit/export/download", method = RequestMethod.POST)
    @ResponseBody
    public String navdbGroupExport( @RequestParam(value = "list[]") List<String> list,@PathVariable String groupIdent,HttpServletResponse response) throws Exception 
        {
            try
            {
                System.out.println(groupIdent);
                System.out.println(list);
                response.setContentType("text/csv");
                String reportName = groupIdent+".csv";
                System.out.println(reportName);
                response.setHeader("Content-disposition", "attachment;filename="+reportName);

                Iterator<String> iter = list.iterator();
                while (iter.hasNext()) {
                    String outputString = (String) iter.next();
                    System.out.println(outputString);
                    response.getOutputStream().print(outputString);
                }
                response.getOutputStream().flush();
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            return "PASS";
        }

我的jquery如下

function exportData() {
    var savedValues = $("#selected-navdb-list>option").map(function () {
        return $(this).val();
    });
    var groupIdent = $('#navdb-group').find(":selected").text();
    alert(groupIdent);
    var navdbs = [];
    for (var i = 0; i < savedValues.length; i++) {
        navdbs.push(savedValues[i]);
    }
    alert(navdbs);
    $.ajax({
        url: "${pageContext.request.contextPath}/navdb/group/" + groupIdent + "/edit/export/download",
        method: "POST",
        data: {
            list: navdbs
        },
        success: function (obj) {
            alert(obj);
            if (obj == "PASS") {
                alert("pass");
            }
        },
        error: function () {
            alert("Error occurred while fetching the navdb's list.");
        }
    });
}

我发现我的代码没有任何问题我不知道为什么不下载不确定我是否错过了什么

当我尝试打印响应时,我很震惊地看到成功阻止的响应具有我附加到响应对象的值

我该如何下载CSV文件? 请帮忙

先谢谢

1 个答案:

答案 0 :(得分:0)

请不要return任何字符串值,而是保留方法返回类型void。检查我粘贴的示例代码,您的实现必须遵循这种模式。

@Controller
public class SpringFileDownload {

    @RequestMapping(value = "/downoadCSV/{groupIdent}", method = RequestMethod.POST)
    @ResponseBody
    public void downloadAttachment(
            @RequestParam("listData") List<String> listData, @PathVariable String groupIdent
            HttpServletResponse servletResponse) {
        try {
            servletResponse.setContentType("text/csv");
            servletResponse.setHeader("Content-Disposition", "attachment; filename=\"myfile.csv\"");
            OutputStream outputStream = servletResponse.getOutputStream();
            StringBuffer stringBuffer = new StringBuffer();
            boolean firstTime = true;
            for(String str:listData){
                if(firstTime){
                    firstTime = false;
                } else {
                    stringBuffer.append(',');
                }
                stringBuffer.append(str);
            }           
            outputStream.write(stringBuffer.toString().getBytes());
            outputStream.flush();
            outputStream.close();
            return;

        } catch (IOException ioEx) {
            servletResponse.setStatus(HttpStatus.NOT_FOUND.value());
            servletResponse.setContentType("application/json");
            servletResponse.getWriter().print("{\"error_message\": \"Error Occured!!!\"}");
        }
    }
}

使用IFrame在JQuery中下载代码:

$.ajax({
    url: "${pageContext.request.contextPath}/download/" + groupIdent,
    method: "POST",
    data: {
        listData: navdbs.toString();
    },
    success: function (obj) {
        $("body").append("<iframe src='" + obj.url+ "' style='display: none;' ></iframe>");
    },
    error: function () {
        alert("Error occurred while fetching the navdb's list.");
    } });

我假设navdbs为数组['asas', 'asasrwer', 'sgdhd']

首先通过点击网址从浏览器进行测试,它应该会显示下载弹出窗口。

我的建议是使用"string",而不是依赖于http status code值来检测成功或失败。如果需要返回字符串,则可以使用servletResponse.getWriter().print("your_text")。这应该适合你。

如果您遇到进一步的问题,请随时发表评论!