解决ajax提交下载问题

通常情况下,无法利用ajax提交下载功能,ajax方式下载文件时无法触发浏览器打开保存文件对话框,也就无法将下载的文件保存到硬盘上,这是因为ajax方式请求的数据只能存放在javascipt内存空间,可以通过javascript访问,但是无法保存到硬盘,因为javascript不能直接和硬盘交互,否则将是一个安全问这里便可以采用构建表单的形式进行下载:

前端代码如下:

<a class="layui-btn layui-btn-normal" onclick="downloadReport()">下载报表</a>

<script>
function downloadReport() {
    var url = "/poi";
    var form = $("<form></form>").attr("action", url).attr("method", "post");
    form.append($("<input></input>").attr("type", "hidden"));
    form.appendTo('body').submit().remove();
}
</script>

服务端代码如下:

controller:

    @ResponseBody
    @RequestMapping("/poi")
    public void poi(HttpServletResponse response){
        String[] rowName = {"id","姓名","city","用户名","省份"};
        List<Object[]> dataList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Object[] element = {i,i+1,i+2,i+3,i+4};
            dataList.add(element);
        }
        POIUtil utils = new POIUtil("测试", rowName, dataList );
        try {
            utils.export(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

向HttpServletResponse内写入流:

byte[] data = workbook.getBytes();
// 给出位置选择框
String headStr = "attachment; filename=\"" + fileName + "\"";
response.reset();
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", headStr);
response.addHeader("Content-Length", "" + data.length);

OutputStream out = new BufferedOutputStream(response.getOutputStream());
out.write(data);
out.flush();
out.close();
response.flushBuffer();

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页