请让我烦恼一个问题。我需要下载在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的简单window.location解决了问题,但是我的参数太大了,GET无法解决。

最佳答案

@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);
    }
}

08-18 17:44
查看更多