JS中使用Fetch发起POST请求,JSON格式参数下载附件

2 篇文章 0 订阅

由于使用Ajax不能下载附件,下载接口中是调用已经写好的查询数据逻辑方法,查询接口为POST请求,请求参数为JSON格式。所以不能直接使用 Form表单方式提交数据。

一、JS代码

在js文件中增加以下方法

/**
 * POST请求,JSON格式参数传参下载附件
 *
 * @param url 下载附件API请求地址
 * @param params 请求参数(JSON格式)
 * @returns {Promise<Response>}
 */
function apiDownload (url, params) {
    return fetch(url,{
        method: 'POST',
        headers: {
            'Accept': 'application/json, */*',
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'cache': 'default',
            'x-ajax': 'true'
        },
        'credentials': 'include', //表示请求是否携带cookie
        body: params
    }).then(function (response) {
        if (response.ok) {
            response.blob().then((blob) => {
                const a = window.document.createElement('a');
                const downUrl = window.URL.createObjectURL(blob);// 获取 blob 本地文件连接 (blob 为纯二进制对象,不能够直接保存到磁盘上)
                const filename = response.headers.get('Content-Disposition').split('filename=')[1].split('.');
                a.href = downUrl;
                a.download = `${decodeURI(filename[0])}.${filename[1]}`;
                a.click();
                window.URL.revokeObjectURL(downUrl);
            });
            return {state: 1}
        } else {
            throw new Error('下载失败')
        }
    })
}

js方法调用

function download(){
	// getParam() 方法为获取请求参数方法 
    var requestParams = getParam();
    if (requestParams != null && requestParams.length >0){
        var param = {
            paramList: requestParams
        }
        // 配置下载接口请求地址
        var url = "view/bond/download.do";
     	// 调用Fetch 下载附件方法,请求参数为JSON格式
        apiDownload(url, JSON.stringify(param));
    }
}

二、Java代码

由于后端项目比较老,前人对控制层做了封装,不能直接使用 @RequestBody 进行自定义参数封装。所以使用 BufferedReader 获取POST请求的JOSN格式数据

/**
     * 下载
     *
     * @param response
     * @param session
     */
    @RequestMapping(value="download")
    public void download(HttpServletRequest request, HttpServletResponse response, HttpSession session)
            throws Exception {
        Map<String, String> resultMap = new HashMap<>();
        // 根据session判断是否登录
        WordUsers user = (WordUsers) session.getAttribute("user");
        if (user != null) {
        	// 判断用户是否购买资源
            if (buyDataService.buyStatus(resoureType, user.getUserId()) == 1){
                try {
                    BufferedReader bufferedReader;
                    String str, wholeStr = "";
                    try {
                        bufferedReader = request.getReader();
                        while((str = bufferedReader.readLine()) != null){
                            wholeStr += str;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    String url = apisPluginUrl + "bond/data";
                    HttpClientUtil client = HttpClientUtil.getInstance();

                    String result = client.doPostJson(url, wholeStr);

                    JSONObject jsonObject = JSON.parseObject(result);
                    String code = (String) jsonObject.get("code");
                    if ("1".equals(code)){
                        // 返回文件流
                        response.setContentType("application/x-msdownload;");
                        response.setHeader("Content-disposition", "attachment; filename=" + new Date().getTime() + ".xlsx");
                        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
                        XSSFWorkbook xwb = new XSSFWorkbook();

                        // 将查询的数据,以excel文件方式保存
                        Object objData = jsonObject.get("data");
                        String jsonData = JSON.toJSONString(objData);
                        getExcel(xwb, jsonData);

                        xwb.write(bos);
                        bos.close();
                    }else {
                        resultMap.put("code", "-1");
                        resultMap.put("msg", "调用服务接口错误");
                        responseJson(response, resultMap);
                    }
                } catch (IOException e) {
                    resultMap.put("code", "-1");
                    resultMap.put("msg", "调用服务接口错误");
                    responseJson(response, resultMap);
                }
            }else {
                resultMap.put("code", "-1");
                resultMap.put("msg", "请购买");
                responseJson(response, resultMap);
            }
        }else {
            resultMap.put("code", "-1");
            resultMap.put("msg", "请登录");
            responseJson(response, resultMap);
        }
    }
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值