通过POST将XLS文件下载到Spring MVC [英] Download XLS file via POST to Spring MVC

查看:168
本文介绍了通过POST将XLS文件下载到Spring MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Please I am annoyed with a problem. I need to download a xls created on the fly on the Java.

这是我的客户端代码:

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无法解决。

I don't know how to show the download dialog, if it was GET a simple window.location solve the problem but my parameters can be so big that GET could not resolve.

推荐答案

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

这篇关于通过POST将XLS文件下载到Spring MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆