通过POST将XLS文件下载到Spring MVC

时间:2014-05-05 18:48:36

标签: jquery spring-mvc xls

请烦恼我。我需要在Java上下载一个动态创建的xls。

这是我的客户端代码:

exportToExcel: function(filters, exportData) {
        $.ajax
        ({
            type: "POST",
            url: 'status/exportToExcel',
            async: true,
            data: {columns: exportData, filters: JSON.stringify(filters)},
            success: function (data) {
            var blob = new Blob([data], { "type" : "application/vnd.ms-excel" });
                var objectUrl = URL.createObjectURL(blob);
                window.open(URL.createObjectURL(objectUrl));
        },
        error: function (a,b,c){
        alert(c);
        }
    });
}

这是我的服务方代码:

@ResponseBody
@RequestMapping(value = "exportToExcel")
public void exportToExcel(
        @RequestParam(value = "columns", required = true) List<String> columns,
        @RequestParam(value = "filters", required = false) String filters, HttpServletRequest request){

    request.getHeaders().setContentType(getMediaType(excelFile));
    request.getHeaders().set("Content-Disposition", String.format("attachment; filename=%s.%s", excelFile.getName(), excelFile.getFormat()));

    try {
        FileCopyUtils.copy(new DataInputStream(new FileInputStream(excelFile.getFile())), httpOutputMessage.getBody());
    } catch (IOException e) {
        logger.error("Exception in file download", e);
    }catch(Exception e){
        logger.error("Exception in file download", e);
    }
}

我不知道如何显示下载对话框,如果它是一个简单的窗口。位置解决问题,但我的参数可能太大,以至于GET无法解决。

2 个答案:

答案 0 :(得分:2)

@RequestMapping(value = "/exportToExcel", method = RequestMethod.POST)
@ResponseBody
public void exportToExcel(-, -, -, -, HttpServletRequest request,HttpServletResponse response )
{
    try{
    InputStream inputStream = service.calltoGetInputStream(); //logic to get inputstream
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", "excelfilename.xlsx");
    response.setHeader(headerKey, headerValue);

    try {
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    }catch(Exception e){
        System.out.println("Exception in file download :"+e);
    }
}

答案 1 :(得分:0)

我在POST时解决了我的问题,我将文件保存在一个文件夹中,之后我将路径返回到我的javascript客户端。 使用filena很简单,做一个GET请求。]

exportToExcel: function(filters, exportData) {
        $.ajax
        ({
            type: "POST",
            url: 'status/exportToExcel',
            async: true,
            data: {columns: exportData, filters: JSON.stringify(filters)},
            success: function (data) {
                window.location = 'status/downloadExcel?file='+data;
            },
        });
    }