二维码生成打包下载与浏览器上

引入依赖

 <!-- 导入zxing的依赖 -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.2.1</version>
        </dependency>

编写前端Ajax

var  options={
		//listDates是所需要传递的数据
         url:ctx + "/IGC0302/logCardQrCode",
          data:listDate,
          method:'post'
        }
        
        var config = $.extend(true, { method: 'post' }, options);
        var $iframe = $('<iframe id="down-file-iframe" />');
        var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
        $form.attr('action', config.url);
        //注意下面的name='listMap'是后台接受参数使用
        $form.append('<input type="hidden" name="listMap" value="' + config.data + '" />');
        $iframe.append($form);
        $(document.body).append($iframe);
        $form[0].submit();
        $iframe.remove();
        //结束

控制层

 @ResponseBody
    @PostMapping("/qc_code")
    public void createQcCode(HttpServletResponse response, HttpServletRequest request) throws Exception {
        String[] parameterNames = request.getParameterValues("listMap");
        String[] split = parameterNames[0].split(",");
        //前端接受到的参数
       for (String name : split) {
            System.err.println(name);
        }
        for (String name : split) {
            UtilsMsQrCode.createQRCodeToFolder("测试","D:\\存放文件\\开发上传下载文件存放",name,300,300);

        }
        UtilsMsFiles.folderToZip("D:\\存放文件\\开发上传下载文件存放",response.getOutputStream());
        //删除文件夹
       UtilsMsFiles.deleteDir(new File("D:\\存放文件\\开发上传下载文件存放"));
    }

二维码工具类

 package com.ms.study.demo.msutils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @ClassName: UtilsMsQrCode
 * @Description: 二维码相关的工具类
 * @Date 2021/10/21
 */
public class UtilsMsQrCode {
    private static final String format = "png";// 默认二维码文件格式
    private static final Map<EncodeHintType, Object> hints = new HashMap();// 二维码参数
    /**
     * 黑色
     */
    private static final int BLACK = 0xFF000000;
    /**
     * 白色
     */
    private static final int WHITE = 0xFFFFFFFF;

    static {
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");// 二维码内容字符编码
        hints.put(EncodeHintType.MARGIN, 2);// 二维码与图片边距
    }

    /**
     * 生成二维码图片,生成在指定的文件夹
     *
     * @param content 二维码内容
     * @param path    文件保存路径
     * @param fileNam 文件名称
     * @param width   宽
     * @param height  高
     * @author mashuai
     * @date 2021/10/21 11:32
     */
    public static BitMatrix createQRCodeToFolder(String content, String path, String fileNam, int width, int height) throws WriterException, IOException {
        File file = new File(path);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        Path path2 = Paths.get(path, fileNam + "." + format);
        MatrixToImageWriter.writeToPath(bitMatrix, format, path2);
        return bitMatrix;
    }

    /**
     * 生成带有log图标的二维码
     *
     * @param content
     * @param path
     * @param fileNam
     * @param width
     * @param height
     * @return void
     * @Param logName  log图标的名称
     * @author mashuai
     * @date 2021/10/26 13:29
     */

    public static void createQRCodeToFolderAddLog(String content, String path, String fileNam, int width, int height, String logName) throws WriterException, IOException {
        File file = new File(path);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        BufferedImage image = toBufferedImage(bitMatrix);
        Graphics g = image.createGraphics();
        g.setColor(Color.BLACK);
        Font font = new Font("宋体", Font.PLAIN, 12);
        FontMetrics metrics = g.getFontMetrics(font);
        // 文字在图片中的坐标 这里设置在左下角
        int startX = 0;
        int startY = height - 8;
        g.setFont(font);
        g.drawString(logName, startX, startY);
        g.dispose();
        Path path2 = Paths.get(path, fileNam + "." + format);
        ImageIO.write(image, format, path2.toFile());
    }


    /**
     * 生成二维码内容<br> 将 BitMatrix转换为BufferedImage
     *
     * @param matrix
     * @return
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
            }
        }
        return image;
    }


    /**
     * 生成二维码图片,依流的形式返回给前端下载(get方式请求可以直接下载在浏览器,post需要通过a标签进行下载)
     *
     * @param response response对象
     * @param content  二维码内容
     * @param width    宽
     * @param height   高
     * @author mashuai
     * @date 2021/10/21 13:32
     */
    public static void createQRCodeToWeb(HttpServletResponse response, String content, int width, int height) throws WriterException, IOException {
        response.setContentType("image/png");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        OutputStream stream = response.getOutputStream();
        //获取一个二维码图片
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
        //以流的形式输出到前端
        MatrixToImageWriter.writeToStream(bitMatrix, "png", stream);
    }

    /**
     * 解析二维码。
     * **/


}

文件工具类

package com.ms.study.demo.msutils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @ClassName: UtilsMsFiles
 * @Description: 常见的文件相关的操作
 * @Date 2021/10/21
 */
public class UtilsMsFiles {

    /**
     * 获取文件后缀
     *
     * @param multipartFile
     * @return java.lang.String
     * @author mashuai
     * @date 2021/10/9 16:01
     */

    public static String getFileSuffix(MultipartFile multipartFile) {
        return multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
    }

    /**
     * 通过URL下载对应的文件
     *
     * @param response
     * @param map      map包含两个{fileUrl:[文件的url] , fileName : [文件名,可不填]}
     * @return void
     * @author mashuai
     * @date 2021/10/21 16:02
     */
    public static void downloadFileByUrl(HttpServletResponse response, Map<String, Object> map) throws IOException {
        //输入流和输出流
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            if (StringUtils.isNotEmpty(MapUtils.getString(map, "fileUrl"))) {
                String fileUrl = MapUtils.getString(map, "fileUrl");
                String ext = fileUrl.substring(fileUrl.lastIndexOf(".") + 1).toLowerCase();
                //文件名,如果没有自定义,那么就随机生成名称
                String fileName = MapUtils.getString(map, "fileName");
                if (StringUtils.isEmpty(fileName)) {
                    fileName = String.valueOf(System.currentTimeMillis());
                }
                fileName = fileName + "." + ext;
                URL url = new URL(fileUrl);//
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(3 * 1000);
                //防止屏蔽程序抓取而返回403错误
                conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                inputStream = conn.getInputStream();
                //输出文件到浏览器
                int len = 0;
                // 输出 下载的响应头,如果下载的文件是中文名,文件名需要经过url编码
                response.setContentType("application/x-download");
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setHeader("Cache-Control", "no-cache");
                response.setContentLength(conn.getContentLength());
                outputStream = response.getOutputStream();
                byte[] buffer = new byte[1024];
                while ((len = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, len);
                }
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
    }


    /**
     * 获取某个文件目录下的所有文件,返回文件名构建成的集合
     *
     * @param folderPath 文件夹的路径  "D:\\存放文件\\开发上传下载文件存放\\垃圾分类二维码功"
     * @author mashuai
     * @date 2021/10/21 14:09
     */
    public static List<String> readAllFile(String folderPath) {
        List<String> allFileNameList = new ArrayList<>();
        File file = new File(folderPath);
        //如果文件夹存在,并且是目录的时候
        if (file.isDirectory()) {
            String[] fileNameArr = file.list();
            allFileNameList = new ArrayList<>(Arrays.asList(fileNameArr));
        }
        return allFileNameList;
    }

    /**
     * 将多个文件打包成压缩包。(get方式请求可以直接下载在浏览器,post需要通过a标签进行下载)
     *
     * @param srcFiles
     * @param out          可以通过response.getOutputStream()获取
     * @return void
     * @author mashuai
     * @date 2021/10/21 15:29
     */
    public static void fileToZip( List<File> srcFiles, OutputStream out) throws RuntimeException {
        long start = System.currentTimeMillis();
//        List<File> srcFiles = new ArrayList<>();
//        for (String name : fileNameList) {
//            srcFiles.add(new File(folderPath + "\\" + name));
//        }
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[2 * 1024];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1) {
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            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();
                }
            }
        }
    }

    /**
     * 根据文件夹压缩整个文件
     *
     * @param floderPath 压缩文件夹路径
     * @param out        压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void folderToZip(String floderPath, OutputStream out) throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(floderPath);
            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();
                }
            }
        }
    }

    public static void compress(File folderPath, ZipOutputStream zos, String name) throws Exception {
        byte[] buf = new byte[2 * 1024];
        if (folderPath.isFile()) {
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(folderPath);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = folderPath.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                zos.putNextEntry(new ZipEntry(name + "/"));
                zos.closeEntry();
            } else {
                for (File file : listFiles) {
                    compress(file, zos, name + "/" + file.getName());
                }
            }
        }
    }

    //删除所有文件
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空,可以删除
        return dir.delete();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值