二维码下载

    @Override
    public void dowloadQrcode(Map<String, Object> hashMap) {
        String string = JsonUtil.toString(hashMap);
        String path = System.getProperty("user.dir");
        String encoded = Base64.getEncoder().encodeToString(string.getBytes());
        String fileName=encoded + ".jpg";
        String filePath=path + "/tmp/" + encoded + ".jpg";
        FileInputStream fileInputStream = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        response.reset();
        try {
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
            hints.put(EncodeHintType.MARGIN, 2);
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bm = qrCodeWriter.encode(string, BarcodeFormat.QR_CODE, 200, 200, hints);
            File upload = new File(path, "tmp");
            if (!upload.exists()) {
                upload.mkdirs();
            }
            File file = new File(filePath);
            MatrixToImageWriter.writeToPath(bm, "jpg", file.toPath());
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Content-Length", "" + file.length());
            fileInputStream = new FileInputStream(filePath);
            inputStream = new BufferedInputStream(fileInputStream);
            outputStream = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (Exception e) {
            throw new ServiceException("二维码下载异常");
        } finally {
            try {
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
                File file = new File(filePath);
                if(file.exists()){
                    file.delete();
                }
            } catch (Exception e2) {
                throw new ServiceException("二维码下载流关闭异常");
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值