根据url生成二维码并生成压缩包,前段调用直接下载

package com.example.demo;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.
;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
public class Hello {

//图片保存路径前缀
private static final String BASE_PATH = "D:/zingImage/";
//压缩包保存路径
private static final String ZIP_PATH = "D:/";
private static final String ZIP_NAME = "zingImage.zip";
//图片保存的格式
private static final String Suffix_PATH = ".png";


@RequestMapping("/hello")
public void HelloTest(HttpServletResponse response) throws Exception {

    //生成所有设备的二维码并保存
    saveInspectionImage();
    createCardImgZip(BASE_PATH,ZIP_NAME);
    //下载压缩包
    downLoadZip(ZIP_NAME,ZIP_PATH+ZIP_NAME,response);
}


/**
 * @author 王安其
 * @desrciption 保存二维码图片到指定位置
 * @Date 2019/6/21 14:55
 * @Param [params]
 * @retrun
 */
public void saveInspectionImage() {
    try {
        deleteDir(BASE_PATH);
        //查询所有机号
        List<String> list = new ArrayList<>();
        list.add("http://www.baidu.com");
        list.add("https://www.hao123.com");
        //你的路径
        for (String key : list) {
            String askUrl = key;
            String savePath = BASE_PATH + System.currentTimeMillis() + Suffix_PATH;
            generateQRCodeImage(askUrl, 350, 350, savePath);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}


/**
 * @param text 扫描二维码后访问的路径
 * @param width 二维码宽度
 * @param height 二维码高度
 * @param filePath 图片保存路径
 * @throws WriterException
 * @throws IOException
 */
private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
    QRCodeWriter qrCodeWriter = new QRCodeWriter();
    BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width,height);
    Path path = FileSystems.getDefault().getPath(filePath);
    MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}

public static void deleteDir(String path){
    if (!(new File(path).isDirectory())) {
        new File(path).mkdir();
    }else{

        File file = new File(path);
        String[] content = file.list();//取得当前目录下所有文件和文件夹
        if(content!=null&& content.length>0) {
            for (String name : content) {
                File temp = new File(path, name);
                if (temp.isDirectory()) {//判断是否是目录
                    deleteDir(temp.getAbsolutePath());//递归调用,删除目录里的内容
                    temp.delete();//删除空目录
                } else {
                    temp.delete();
                }
            }
        }
    }
}

/**
 * @param sourcePath
 * @param zipName
 * @return
 */
public void createCardImgZip(String sourcePath, String zipName) {
    String zipPath = ZIP_PATH;
    File sourceFile = new File(sourcePath);
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    ZipOutputStream zos = null;
    try {
        File zipFile = new File(zipPath + "/" + zipName.split("\\.")[0] + ".zip");
        //如果压缩包存在,删除即可
        if (zipFile.exists()) {
            zipFile.delete();
        }
        fos = new FileOutputStream(zipFile);
        zos = new ZipOutputStream(new BufferedOutputStream(fos));
        byte[] bufs = new byte[1024 * 10];
        // create .zip and put pictures in
        File[] sourceFiles = sourceFile.listFiles();
        for(int i=0;i<sourceFiles.length;i++){
            //创建ZIP实体,并添加进压缩包
            ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
            zos.putNextEntry(zipEntry);
            //读取待压缩的文件并写进压缩包里
            fis = new FileInputStream(sourceFiles[i]);
            bis = new BufferedInputStream(fis, 1024*10);
            int read = 0;
            while((read=bis.read(bufs, 0, 1024*10)) != -1){
                zos.write(bufs,0,read);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != bis)
                bis.close();
            if (null != zos)
                zos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * @param fileName 文件名
 * @param path 文件保存路径(含文件名称)
 * @param response
 * @return
 */
public String downLoadZip(String fileName,String path,HttpServletResponse response) {
    try {
        File file = new File(path);
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition",
                "attachment; filename=" + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
        response.setContentLength((int) file.length());
        //定义输出类型
        response.setContentType("application/zip");
        FileInputStream fis = new FileInputStream(file);
        BufferedInputStream buff = new BufferedInputStream(fis);
        //相当于我们的缓存
        byte[] b = new byte[1024];
        //该值用于计算当前实际下载了多少字节
        long k = 0;
        //从response对象中得到输出流,准备下载
        OutputStream myout = response.getOutputStream();
        //开始循环下载
        while (k < file.length()) {
            int j = buff.read(b, 0, 1024);
            k += j;
            myout.write(b, 0, j);
        }
        myout.flush();
        buff.close();
        file.delete();
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值