Ajax 实现导出文件-支持批量

个人感觉前端不行,好多东西记不住,所以只能将遇到的坎以及解决方案记录下,方便以后用到时查找。

首先:ajax不支持流,网上找了好多版本,感觉下面的方案不错,实验了下可行。

前端页面:

 <div class="div-tbl">
        <h1></h1>
        <div class="div-btn">
            <button id="commitClo" class="btn btn-primary">Commit</button>
            <button id="testCommit" class="btn btn-primary">Test</button>
        </div>
    </div>

<script>
     $("#testCommit").on("click",function(){
            var testData = {
                "owner": "FIXDATA",
                "tableName": "L_TBL_USER",
                "tableDescribe": "用户表",
                "autoFlag": "Yes",
                "columnList": [{
                    "columnName": "id",
                    "columnDescribe": "",
                    "columnType": "varchar2(30)",
                    "columnNullFlag": "No",
                    "defaultVal": ""
                }, {
                    "columnName": "name",
                    "columnDescribe": "",
                    "columnType": "VARCHAR2(30)",
                    "columnNullFlag": "No",
                    "defaultVal": ""
                }, {
                    "columnName": "age",
                    "columnDescribe": "",
                    "columnType": "number(2)",
                    "columnNullFlag": "No",
                    "defaultVal": ""
                }],
                "inxList": [{
                    "owner": "FIXDATA",
                    "tableName": "L_TBL_USER",
                    "inxColumnNames": "id",
                    "indexType": "1"
                }],
                "grtList": [{
                    "owner": "FIXDATA",
                    "tableName": "L_TBL_USER",
                    "roleName": "chen",
                    "operateArr": "select,insert,update,delete"
                }]
            };

            $.ajax({
                type: "post",
                url: "/export/orcSql",    //向后端请求数据的url
                data: JSON.stringify(testData) ,
                dataType:"text",//返回数据类型
                //默认application/x-www-form-urlencoded;charset=UTF-8
                //springmvc @RequestBody注解做提交json字符串自动绑定到pojo入参时
                contentType: "application/json;charset=UTF-8",
                success: function (data) {
                    var jsonData = JSON.parse(data);
                    if(jsonData["result"] === "1"){
                        batchDownLoadFile(jsonData["body"]);
                    }

                },error:function (data) {
                    console.log(2222);
                }
            });
        });
</script>

自定义js:

/**
 * AJAX导出文件测试
 * @param obj
 */
function ajaxExportFileTest(obj) {
    $.ajax({
        url : "ajaxExportFileTest",
        type : "post",
        success : function (result) {
            if (result){
                let filename = "ceshi.xlsx";
                let blob = getBlob(result,{type: "application/vnd.ms-excel"});
                let isDown = true;
                let url = downloadBlob(filename,blob,isDown);
                console.log(url);
            }
        }
    });

}

/**
 * 获取Blob
 * @param base64 base64字符串
 * @param contentType 导出格式 MIME 类型
 * @param sliceSize 分割大小
 * @returns {Blob}
 */
function getBlob(base64, contentType, sliceSize) {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;

    let byteCharacters = atob(base64);
    let byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        let slice = byteCharacters.slice(offset, offset + sliceSize);

        let byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        let byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    return new Blob(byteArrays, {type: contentType});
}

/**
 * 下载文件
 * @param fileName 文件名
 * @param blob BLOB对象
 * @param isDown 是否下载,默认不下载
 * @returns {string} 返回url
 */
function downloadBlob(fileName, blob,isDown){
    //默认不下载,返回url
    //判断是直接下载还是返回对应的URL
    let url = URL.createObjectURL(blob);
    if (isDown){
        //如果是直接下载,利用a标签来实现下载
        let docEle = document;
        let link = docEle.createElement("a");
        link.innerHTML = fileName;
        link.download = fileName;
        link.href = url;
        docEle.getElementsByTagName("body")[0].appendChild(link);
        link.click();
        $(link).remove();
    }
    return url;
}

function batchDownLoadFile(objArr){
   $.each(objArr,function(key,val){
       downLoadFile(val["fileName"],val["content"]);
   })
}

function downLoadFile(fileName,content){
    let blob = getBlob(content,{type: "application/octet-stream"});
    let isDown = true;
    let url = downloadBlob(fileName,blob,isDown);
}

后端实现:

package com.example.demo.controller;

import com.example.demo.dto.TableDto;
import com.example.demo.service.TestService;
import com.example.demo.util.CommonCollectionUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/export")
public class ExportController {

    @Resource
    private TestService testService;

    @ResponseBody
    @RequestMapping(value = "/orcSql",method = RequestMethod.POST)
    public Map<String, Object> export(@RequestBody TableDto dto, HttpServletResponse response) throws IOException {
        System.out.println(dto);

        response.setStatus(HttpStatus.OK.value());

        Map<String, Object> resultMap = CommonCollectionUtils.newHashMapInstance();

        List<Map<String,String>> bodyList = new ArrayList<Map<String,String>>();
        Map<String,String> fileMap1 = CommonCollectionUtils.newHashMapInstance();
        fileMap1.put("fileName","11111.sql");
        fileMap1.put("content",testService.exportExcelFileBase64Str("Hello,1111"));

        Map<String,String> fileMap2 = CommonCollectionUtils.newHashMapInstance();
        fileMap2.put("fileName","2222.sql");
        fileMap2.put("content",testService.exportExcelFileBase64Str("Hello,2222"));

        bodyList.add(fileMap1);
        bodyList.add(fileMap2);

        resultMap.put("result","1");
        resultMap.put("body",bodyList);

        return resultMap;
    }

    @PostMapping(value = "/ajaxExportFileTest")
    @ResponseBody
    public String ajaxExportFileTest(HttpServletResponse response){
        response.setStatus(HttpStatus.OK.value());
        return testService.exportExcelFileBase64Str("Hello,Heoo!");
    }
}

测试:

 

转载于:https://www.cnblogs.com/xiaozhuanfeng/p/11012059.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值