java使用feign接口下载文件

1、feign接口定义(注意:Response 导包)

import feign.Response;
    /**
     * 导出定义
     */
    @PostMapping(value="/xx/export")
    Response export(@RequestBody JSONObject data);

2、接收feign的流,写入response中


    /**
     * 导出
     */
    @PostMapping("export")
    public void export(HttpServletRequest request, HttpServletResponse response) {
        //调feign获取feignResponse
        Response feignResponse = xxxFeign.export(param);
        try {
            InputStream inputStream = feignResponse.body().asInputStream();
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("导出_" + System.currentTimeMillis() + ".zip", "UTF-8"));
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            os = response.getOutputStream();
            byte[] b = toByteArray(inputStream);

            //测试代码
            writeToLocal("D:\\partner-resource\\导出_"+System.currentTimeMillis()+".zip",b);
            os.write(b);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/text;charset=UTF-8");
            this.writeResponse(response, this.convertException(e));
        }finally {
            try {
                os.close();
            } catch (Exception e) {
            }
        }
    }


    /**
     * InputStream 转换成byte[]
     * @param input
     * @return
     * @throws IOException
     */
    private static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }

    /**
     * 将bytes写入本地文件(测试代码)
     * @param destination
     * @param bytes
     * @throws IOException
     */
    private static void writeToLocal(String destination, byte[] bytes)
            throws IOException {
        FileOutputStream downloadFile = new FileOutputStream(destination);
        downloadFile.write(bytes);
        downloadFile.flush();
        downloadFile.close();
    }

java将InputStream或bytes写入本地文件(传送门)

评论 30
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

多来哈米

还可以打赏???来试一毛

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值