springboot + minio 实现批量导出二维码

569 阅读2分钟

批量导出二维码

第一步引入对应的jar包

<!--如果是非 web 应用则导入 core 包即可,如果是 web 应用,则 core 与 javase 一起导入。-->
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.3</version>
</dependency>
 <dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.3</version>
</dependency>

实现代码

工具类

package org.sq.common.utils;

import com.github.binarywang.utils.qrcode.MatrixToImageWriter;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class QRCodeEvents {

    private static final int BUFFER_SIZE = 2 * 1024;

    public static File moundQrCode(Long moundId) throws WriterException, IOException {
        String text = "http://pms.kwkj.net/app/details.html?moundId=" + moundId;
        BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 1024, 1024);
        File outputFile = new File(moundId + ".png");
        MatrixToImageWriter.writeToFile(bitMatrix, "png", outputFile);
        return outputFile;
    }

    public static void downloadFile(String remoteFilePath, String localFilePath) {
        URL urlfile;
        HttpURLConnection httpUrl;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File f = new File(localFilePath);
        try {
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            bis = new BufferedInputStream(httpUrl.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 2048;
            byte[] b = new byte[len];
            while ((len = bis.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            bos.flush();
            bis.close();
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void toZip(String srcDir, OutputStream out) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            compress(sourceFile, zos, sourceFile.getName());
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) + " ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static void compress(File sourceFile, ZipOutputStream zos, String name) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        if (sourceFile.isFile()) {
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                // 空文件夹的处理
                zos.putNextEntry(new ZipEntry(name + "/"));
                // 没有文件,不需要文件的copy
                zos.closeEntry();
            } else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                    // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                    compress(file, zos, name + "/" + file.getName());
                }
            }
        }
    }
}

实现逻辑

@PostMapping("qrDownloadByIds")
    @ApiOperation("导出二维码")
    public R<JSONObject> qrDownloadByIds(@ApiParam(value = "主键集合", required = true) @RequestParam String ids, SqUser user) throws IOException, WriterException {
        //创建文件夹
        String path = user.getUserId().toString();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }
        List<Inn> moundList = innService.listByIds(Arrays.asList(ids.split(",")));
        for (Inn mound : moundList) {
            //判断一下是否生成二维码
            if (StringUtils.isBlank(mound.getQrPath())) {
                //生成二维码
                File qrfile = QRCodeEvents.moundQrCode(mound.getId());
                SqFile sqFile = ossBuilder.template().putFile(qrfile.getName(), new FileInputStream(qrfile));
                mound.setQrPath(sqFile.getLink());
                innService.updateById(mound);
                file.delete();


                QRCodeEvents.downloadFile(mound.getQrPath(), path + "/" + mound.getInnName() + ".png");
            } else {
                QRCodeEvents.downloadFile(mound.getQrPath(), path + "/" + mound.getInnName() + ".png");
            }

        }

        if (moundList.size() > 0) {
            File zip = new File(path + ".zip");
            FileOutputStream outputStream = new FileOutputStream(zip);
            QRCodeEvents.toZip(path, outputStream);

            SqFile sqFile = ossBuilder.template().putFile(zip.getName(), new FileInputStream(zip));

            zip.delete();
            File[] files = file.listFiles();
            assert files != null;
            for (File value : files) {
                value.delete();
            }
            file.delete();

            JSONObject data = new JSONObject();
            data.put("link", sqFile.getLink());
            data.put("fileName", sqFile.getName());

            return R.data(data);
        }

        return R.fail("未找到二维码");
    }