引入依赖
<!-- 导入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={
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);
$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.*;
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);
}
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;
}
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());
}
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;
}
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;
public class UtilsMsFiles {
public static String getFileSuffix(MultipartFile multipartFile) {
return multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
}
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);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
inputStream = conn.getInputStream();
int len = 0;
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();
}
}
}
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;
}
public static void fileToZip( List<File> srcFiles, OutputStream out) throws RuntimeException {
long start = System.currentTimeMillis();
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();
}
}
}
}
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()) {
zos.putNextEntry(new ZipEntry(name));
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();
}
}