java生成二维码 && OSS上传文件

it2026-04-20  4

实现代码

pom.xml依赖

<!-- 二维码 --> <dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> <scope>compile</scope> </dependency> <!-- aliyun oss --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.6.0</version> </dependency>

二维码工具类

BarcodeUtils

package com.mybatisplus.utils; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.util.HashMap; import java.util.Map; /** * @author : * @date :Created in 2020/7/27 11:35 * @Time: 11:35 * @description: * @modified By: * @version: $ */ public class BarcodeUtils { private static final int QRCOLOR = 0xFF000000; // 二维码颜色 默认是黑色 private static final int BGWHITE = 0xAABBCCDD; // 背景颜色 private static final int WIDTH = 500; // 二维码宽 private static final int HEIGHT = 500; // 二维码高 private static final int WORDHEIGHT = 540; // 加文字二维码高 /** * 用于设置QR二维码参数 */ private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() { private static final long serialVersionUID = 1L; { // 设置QR二维码的纠错级别(H为最高级别)具体级别信息 put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 设置编码方式 put(EncodeHintType.CHARACTER_SET, "utf-8"); put(EncodeHintType.MARGIN, 0); } }; /** * 设置 Graphics2D 属性 (抗锯齿) * @param graphics2D */ private static void setGraphics2D(Graphics2D graphics2D){ graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT); Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER); graphics2D.setStroke(s); } /** * @description 生成带logo的二维码图片 二维码下面带文字 * @param logoFile loge图片的路径 * @param bgFile 背景图片的路径 * @param codeFile 图片输出路径 * @param qrUrl 二维码内容 * @param words 二维码下面的文字 */ public static void drawLogoQRCode(String logoFile,String bgFile, File codeFile, String qrUrl, String words) { try { MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数 BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB); // // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色 for (int x = 0; x < WIDTH; x++) { for (int y = 0; y < HEIGHT; y++) { image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE); } } //login BufferedImage qrCodeWithLogoNoBg = QrCodeUtil.addLogo(image,logoFile); //无logo,无背景二维码 //BufferedImage qrCodeNoLogoWithBg = QrCodeUtil.addBgImg(qrCodeWithLogoNoBg, bgFile, 0, 0); //添加二维码文字内容 BufferedImage qrCodeAddText = QrCodeUtil.addText(qrCodeWithLogoNoBg, words, 50); ImageIO.write(qrCodeAddText, "png", codeFile); } catch (Exception e) { e.printStackTrace(); } } // public static void main(String[] args) { // //logo // String logoFile = "C:\\Users\\admin\\Pictures\\rz\\6d7f59.jpeg"; // //背景图片 // String bgFile = "C:\\Users\\admin\\Pictures\\rz\\login.png"; // //生成图片 // File qrCodeFile = new File("C:\\Users\\admin\\Pictures\\rz\\sfasfa.jpeg"); // //二维码内容 // String url = "https://www.baidu.com"; // //二维码下面的文字 // String words = "学生: XXXXXX"; // drawLogoQRCode(logoFile,bgFile, qrCodeFile, url, words); // } }

QrCodeUtil

package com.mybatisplus.utils; import cn.hutool.extra.qrcode.BufferedImageLuminanceSource; import com.google.zxing.*; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; /** * @author :admin * @date :Created in 2020/7/27 10:16 * @Time: 10:16 * @description:二维码工具类 * @modified By: * @version: 1.0$ */ public class QrCodeUtil { //0x,透明度,R,G,B private static final int BLACK = 0xAABBCCDD; private static final int WHITE = 0x00FFFFFF; /** * 二维码图片生成 * @param matrix * @return */ public 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) ? BLACK : WHITE); } } return image; } /** * 二维码输出为文件 * @param image 二维码图片 * @param format 二维码图片格式 * @param filePath 二维码保存路径 * @throws IOException */ public static void writeToFile(BufferedImage image, String format, String filePath) throws IOException { File outputFile = new File(filePath); if (!outputFile.exists()) { outputFile.mkdirs(); } if (!ImageIO.write(image, format, outputFile)) { throw new IOException("不能转换成" + format ); } } /** * 二维码添加logo(logo占二维码1/5) * @param image 二维码图片 * @param logoFilePath logo图片路径 * @return * @throws IOException */ public static BufferedImage addLogo(BufferedImage image, String logoFilePath) throws IOException { File file = new File(logoFilePath); if (!file.exists()) { throw new IOException("logo文件不存在"); } BufferedImage logo = ImageIO.read(file); Graphics2D graph = image.createGraphics(); graph.drawImage(logo, image.getWidth() * 2 / 5, image.getHeight() * 2 / 5 , image.getWidth() * 2 / 10, image.getHeight() * 2 / 10, null); graph.dispose(); return image; } /** * 二维码添加背景 * @param image 二维码图片 * @param bgFilePath 背景图片路径 * @param x 维码左顶点在背景图片的X坐标 * @param y 二维码左顶点在背景图片的Y坐标 * @return * @throws IOException */ public static BufferedImage addBgImg(BufferedImage image, String bgFilePath, int x, int y) throws Exception { File file = new File(bgFilePath); if (!file.exists()) { throw new IOException("背景图片不存在"); } BufferedImage bgImg = ImageIO.read(file); if(x < 0) { x = 0; } if(y < 0) { y = 0; } // if(bgImg.getWidth() < image.getWidth() || bgImg.getHeight() <image.getHeight()) { // throw new Exception("背景图片小于二维码尺寸"); // } // if(bgImg.getWidth() < x + image.getWidth() || bgImg.getHeight() < y + bgImg.getHeight()) { // throw new Exception("以背景的("+x+","+y+")作为二维码左上角不能容下整个二维码"); // } Graphics2D graph = bgImg.createGraphics(); graph.drawImage(image, x, y, image.getWidth(), image.getHeight(), null); graph.dispose(); return bgImg; } /** * 二维码底部添加文本(只限一行,没有换行) * @param image 二维码图片 * @param text 文本内容 * @param fontSize 写入文本的字体 * @return */ public static BufferedImage addText(BufferedImage image, String text, int fontSize) { int outImageWidth = image.getWidth(); int outImageHeight = image.getHeight() + fontSize + 10; BufferedImage outImage = new BufferedImage(outImageWidth, outImageHeight, BufferedImage.TYPE_INT_RGB); Graphics2D graph = outImage.createGraphics(); //填充为白色背景 graph.setColor(Color.white); graph.fillRect(0 ,0 , outImageWidth, outImageHeight); //将二维码画入 graph.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null); //添加文本 graph.setColor(Color.black); Font font = new Font("楷体", Font.BOLD, fontSize);//字体,字型,字号 graph.setFont(font); //文本水平,垂直居中 FontRenderContext frc = new FontRenderContext(null, true, true); Rectangle2D r2D = font.getStringBounds(text, frc); int rWidth = (int) Math.round(r2D.getWidth()); int a = (outImageWidth - rWidth) / 2; graph.drawString(text,a, outImageHeight - 5);//x,y为左下角坐标 graph.dispose(); return outImage; } /** * 生成二维码(无logo,无背景) * 根据内容,生成指定宽高、指定格式的二维码图片 * @param text 内容 * @param width 宽 * @param height 高 * @return * @throws Exception */ public static BufferedImage encodeQrCode(String text, int width, int height) throws WriterException, IOException { //设置二维码配置 Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); // 设置QR二维码的纠错级别,指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%) hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); hints.put(EncodeHintType.MARGIN, 0);// 白边 //创建比特矩阵(位矩阵)的QR码编码的字符串 BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints); //二维码图片生成 BufferedImage qrCodeImg = toBufferedImage(bitMatrix); return qrCodeImg; } /** * 解析二维码 * @param image 读入的二维码图片 * @return */ public static String decodeQrCode(BufferedImage image) { String qrCodeContent = null; try { LuminanceSource source = new BufferedImageLuminanceSource(image); Binarizer binarizer = new HybridBinarizer(source); BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer); Map<DecodeHintType, Object> hints = new HashMap<DecodeHintType, Object>(); hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); Result result = new MultiFormatReader().decode(binaryBitmap, hints);// 对图像进行解码 qrCodeContent= result.getText(); } catch (Exception e) { e.printStackTrace(); } return qrCodeContent; } private static final int QRCOLOR = 0xFF000000; // 二维码颜色 默认是黑色 private static final int BGWHITE = 0xAABBCCDD; // 背景颜色 private static final int WIDTH = 500; // 二维码宽 private static final int HEIGHT = 500; // 二维码高 private static final int WORDHEIGHT = 540; // 加文字二维码高 /** * 用于设置QR二维码参数 */ private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() { private static final long serialVersionUID = 1L; { // 设置QR二维码的纠错级别(H为最高级别)具体级别信息 put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 设置编码方式 put(EncodeHintType.CHARACTER_SET, "utf-8"); put(EncodeHintType.MARGIN, 0); } }; /** * 设置 Graphics2D 属性 (抗锯齿) * @param graphics2D */ private static void setGraphics2D(Graphics2D graphics2D){ graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT); Stroke s = new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_MITER); graphics2D.setStroke(s); } /** * @description 生成带logo的二维码图片 二维码下面带文字 * @param logoFile loge图片的路径 * @param bgFile 背景图片的路径 * @param codeFile 图片输出路径 * @param qrUrl 二维码内容 * @param words 二维码下面的文字 */ public static void drawLogoQRCode(String logoFile,String bgFile, File codeFile, String qrUrl, String words) { try { MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数 BitMatrix bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_ARGB); // // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色 for (int x = 0; x < WIDTH; x++) { for (int y = 0; y < HEIGHT; y++) { image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE); } } //login BufferedImage qrCodeWithLogoNoBg = QrCodeUtil.addLogo(image,logoFile); //无logo,无背景二维码 BufferedImage qrCodeNoLogoWithBg = QrCodeUtil.addBgImg(qrCodeWithLogoNoBg, bgFile, 0, 0); BufferedImage qrCodeAddText = QrCodeUtil.addText(qrCodeNoLogoWithBg, words, 50); ImageIO.write(qrCodeAddText, "png", codeFile); } catch (Exception e) { e.printStackTrace(); } } }

文件处理工具类

FileUtils 

package com.mybatisplus.utils; import cn.hutool.core.util.IdUtil; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItem; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import java.io.*; import java.net.URL; import java.nio.file.Files; /** * @author :admin * @date :Created in 2020/7/22 17:10 * @Time: 17:10 * @description:文件处理工具类 * @modified By: * @version: 1.0$ */ public class FileUtils { /** * 类型转换 * @param file * @return * @throws Exception */ public static File multipartFileToFile(MultipartFile file) throws Exception { File toFile = null; if (file.equals("") || file.getSize() <= 0) { file = null; } else { InputStream ins = null; ins = file.getInputStream(); toFile = new File(file.getOriginalFilename()); inputStreamToFile(ins, toFile); ins.close(); } return toFile; } /** * 类型转换 * @param file * @return * @throws Exception */ public static MultipartFile FileToMultipartFile(File file) throws Exception { //会生成文件 // FileInputStream input = new FileInputStream(file); // return new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(input)); FileItem fileItem = new DiskFileItem("mainFile", Files.probeContentType(file.toPath()), false, file.getName(), (int) file.length(), file.getParentFile()); InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream(); IOUtils.copy(input, os); return new CommonsMultipartFile(fileItem); } //获取流文件 private static void inputStreamToFile(InputStream ins, File file) { try { OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); ins.close(); } catch (Exception e) { e.printStackTrace(); } } /** * MultipartFile转File */ public static File toFile(MultipartFile multipartFile){ // 获取文件名 String fileName = multipartFile.getOriginalFilename(); // 获取文件后缀 String prefix="."+getExtensionName(fileName); File file = null; try { // 用uuid作为文件名,防止生成的临时文件重复 file = File.createTempFile(IdUtil.simpleUUID(), prefix); // MultipartFile to File multipartFile.transferTo(file); } catch (IOException e) { e.printStackTrace(); } return file; } /** * 获取文件扩展名,不带 . */ public static String getExtensionName(String filename) { if ((filename != null) && (filename.length() > 0)) { int dot = filename.lastIndexOf('.'); if ((dot >-1) && (dot < (filename.length() - 1))) { return filename.substring(dot + 1); } } return filename; } /**   * @Description: 网络资源转file,用完以后必须删除该临时文件   * @param fileUrl 资源地址   * @author: 赵兴炎   * @date: 2019年7月10日   * @return: 返回值   */ public static File urlToFile(String fileUrl) { String path = System.getProperty("user.dir"); File upload = new File(path, "tmp"); if (!upload.exists()) { upload.mkdirs(); } return urlToFile(fileUrl,upload); } /** * @Description: 网络资源转file,用完以后必须删除该临时文件 * @param fileUrl 资源地址 * @param upload 临时文件路径 * @author: 赵兴炎 * @date: 2019年7月10日 * @return: 返回值 */ public static File urlToFile(String fileUrl,File upload) { String fileName = fileUrl.substring(fileUrl.lastIndexOf("/")); FileOutputStream downloadFile = null; InputStream openStream = null; File savedFile = null; try { savedFile = new File(upload.getAbsolutePath() + fileName); URL url = new URL(fileUrl); java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection(); openStream = connection.getInputStream(); int index; byte[] bytes = new byte[1024]; downloadFile = new FileOutputStream(savedFile); while ((index = openStream.read(bytes)) != -1) { downloadFile.write(bytes, 0, index); downloadFile.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (openStream != null) { openStream.close(); } if (downloadFile != null) { downloadFile.close(); } } catch (Exception e) { e.printStackTrace(); } } return savedFile; } /** * 判断文件名是否带盘符,重新处理 * @param fileName * @return */ public static String getFileName(String fileName){ //判断是否带有盘符信息 // Check for Unix-style path int unixSep = fileName.lastIndexOf('/'); // Check for Windows-style path int winSep = fileName.lastIndexOf('\\'); // Cut off at latest possible point int pos = (winSep > unixSep ? winSep : unixSep); if (pos != -1) { // Any sort of path separator found... fileName = fileName.substring(pos + 1); } //替换上传文件名字的特殊字符 fileName = fileName.replace("=","").replace(",","").replace("&",""); return fileName; } }

OSS工具类

OssBootUtil

endPoint、accessKeyId、accessKeySecret、bucketName、staticDomain 根据自己阿里云的参数自己配置 package com.mybatisplus.utils; import com.aliyun.oss.ClientConfiguration; import com.aliyun.oss.OSSClient; import com.aliyun.oss.common.auth.DefaultCredentialProvider; import com.aliyun.oss.model.CannedAccessControlList; import com.aliyun.oss.model.OSSObject; import com.aliyun.oss.model.PutObjectResult; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.commons.fileupload.FileItemStream; import org.springframework.web.multipart.MultipartFile; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLDecoder; import java.util.Date; import java.util.UUID; /** * @Description: 阿里云 oss 上传工具类(高依赖版) */ @Data @Slf4j public class OssBootUtil { private static String endPoint = ""; private static String accessKeyId = ""; private static String accessKeySecret = ""; private static String bucketName = ""; private static String staticDomain = ""; /** * oss 工具客户端 */ private static OSSClient ossClient = null; /** * 上传文件至阿里云 OSS * 文件上传成功,返回文件完整访问路径 * 文件上传失败,返回 null * * @param file 待上传文件 * @param fileDir 文件保存目录 * @return customBucket 中的相对文件路径 */ public static String upload(MultipartFile file, String fileDir,String customBucket) { String FILE_URL = null; initOSS(endPoint, accessKeyId, accessKeySecret); StringBuilder fileUrl = new StringBuilder(); String newBucket = bucketName; if(oConvertUtils.isNotEmpty(customBucket)){ newBucket = customBucket; } try { //判断桶是否存在,不存在则创建桶 if(!ossClient.doesBucketExist(newBucket)){ ossClient.createBucket(newBucket); } // 获取文件名 String orgName = file.getOriginalFilename(); orgName = FileUtils.getFileName(orgName); String fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf(".")); if (!fileDir.endsWith("/")) { fileDir = fileDir.concat("/"); } fileUrl = fileUrl.append(fileDir + fileName); if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) { FILE_URL = staticDomain + "/" + fileUrl; } else { FILE_URL = "https://" + newBucket + "." + endPoint + "/" + fileUrl; } PutObjectResult result = ossClient.putObject(newBucket, fileUrl.toString(), file.getInputStream()); // 设置权限(公开读) ossClient.setBucketAcl(newBucket, CannedAccessControlList.PublicRead); if (result != null) { log.info("------OSS文件上传成功------" + fileUrl); } } catch (IOException e) { e.printStackTrace(); return null; } return FILE_URL; } /** * 文件上传 * @param file * @param fileDir * @return */ public static String upload(MultipartFile file, String fileDir) { return upload(file, fileDir,null); } /** * 上传文件至阿里云 OSS * 文件上传成功,返回文件完整访问路径 * 文件上传失败,返回 null * @param file 待上传文件 * @param fileDir 文件保存目录 * @return oss 中的相对文件路径 */ public static String upload(FileItemStream file, String fileDir) { String FILE_URL = null; initOSS(endPoint, accessKeyId, accessKeySecret); StringBuilder fileUrl = new StringBuilder(); try { String suffix = file.getName().substring(file.getName().lastIndexOf('.')); String fileName = UUID.randomUUID().toString().replace("-", "") + suffix; if (!fileDir.endsWith("/")) { fileDir = fileDir.concat("/"); } fileUrl = fileUrl.append(fileDir + fileName); if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) { FILE_URL = staticDomain + "/" + fileUrl; } else { FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl; } PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(), file.openStream()); // 设置权限(公开读) ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead); if (result != null) { log.info("------OSS文件上传成功------" + fileUrl); } } catch (IOException e) { e.printStackTrace(); return null; } return FILE_URL; } /** * 删除文件 * @param url */ public static void deleteUrl(String url) { deleteUrl(url,null); } /** * 删除文件 * @param url */ public static void deleteUrl(String url,String bucket) { String newBucket = bucketName; if(oConvertUtils.isNotEmpty(bucket)){ newBucket = bucket; } String bucketUrl = ""; if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) { bucketUrl = staticDomain + "/" ; } else { bucketUrl = "https://" + newBucket + "." + endPoint + "/"; } url = url.replace(bucketUrl,""); ossClient.deleteObject(newBucket, url); } /** * 删除文件 * @param fileName */ public static void delete(String fileName) { ossClient.deleteObject(bucketName, fileName); } /** * 获取文件流 * @param objectName * @param bucket * @return */ public static InputStream getOssFile(String objectName,String bucket){ InputStream inputStream = null; try{ String newBucket = bucketName; if(oConvertUtils.isNotEmpty(bucket)){ newBucket = bucket; } initOSS(endPoint, accessKeyId, accessKeySecret); OSSObject ossObject = ossClient.getObject(newBucket,objectName); inputStream = new BufferedInputStream(ossObject.getObjectContent()); }catch (Exception e){ log.info("文件获取失败" + e.getMessage()); } return inputStream; } /** * 获取文件流 * @param objectName * @return */ public static InputStream getOssFile(String objectName){ return getOssFile(objectName,null); } /** * 获取文件外链 * @param bucketName * @param objectName * @param expires * @return */ public static String getObjectURL(String bucketName, String objectName, Date expires) { initOSS(endPoint, accessKeyId, accessKeySecret); try{ if(ossClient.doesObjectExist(bucketName,objectName)){ URL url = ossClient.generatePresignedUrl(bucketName,objectName,expires); return URLDecoder.decode(url.toString(),"UTF-8"); } }catch (Exception e){ log.info("文件路径获取失败" + e.getMessage()); } return null; } /** * 初始化 oss 客户端 * * @return */ private static OSSClient initOSS(String endpoint, String accessKeyId, String accessKeySecret) { if (ossClient == null) { ossClient = new OSSClient(endpoint, new DefaultCredentialProvider(accessKeyId, accessKeySecret), new ClientConfiguration()); } return ossClient; } /** * 上传文件到oss * @param stream * @param relativePath * @return */ public static String upload(InputStream stream, String relativePath) { String FILE_URL = null; String fileUrl = relativePath; initOSS(endPoint, accessKeyId, accessKeySecret); if (oConvertUtils.isNotEmpty(staticDomain) && staticDomain.toLowerCase().startsWith("http")) { FILE_URL = staticDomain + "/" + relativePath; } else { FILE_URL = "https://" + bucketName + "." + endPoint + "/" + fileUrl; } PutObjectResult result = ossClient.putObject(bucketName, fileUrl.toString(),stream); // 设置权限(公开读) ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead); if (result != null) { log.info("------OSS文件上传成功------" + fileUrl); } return FILE_URL; } }

Controller

package com.mybatisplus.controller; import cn.hutool.core.io.FileUtil; import com.mybatisplus.utils.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.File; /** * @author :admin * @Time: 9:34 * @description:二维码生成 * @modified By: * @version: 1.0$ */ @Api(tags="二维码生成") @RestController @RequestMapping("/QrCode") public class QrCodeController { @ApiOperation(value="生成二维码", notes="生成二维码") @GetMapping(value = "/generate") public ResponseEntityT<?> GenerateQrCode(@RequestParam(name="url",required=true) String url) { try { //背景图片 File bgFile = FileUtils.urlToFile("https://profile.csdnimg.cn/E/9/C/1_tangcv"); //二维码地址 String path = System.getProperty("user.dir"); File qrCodeFile = new File(path + DateUtils.getDate().getTime() + ".png");//Win 服务器方式 //File qrCodeFile = new File("/sys/exam/tmp/" + DateUtils.getDate().getTime() + ".png");//Linux 服务器方式 if (!qrCodeFile.exists()) { qrCodeFile.mkdirs(); } //二维码内容 //String url = "我是二维码内容"; //二维码下方文字 String words = "二维码下方文字"; BarcodeUtils.drawLogoQRCode(bgFile.getPath(),null, qrCodeFile, url, words); //上传文件阿里云 String OssUrl = OssBootUtil.upload(FileUtils.FileToMultipartFile(qrCodeFile),"QrCode"); // //删除临时文件 FileUtil.del(bgFile); FileUtil.del(qrCodeFile); return ResponseEntityT.OK(OssUrl); } catch (Exception e) { e.printStackTrace(); return ResponseEntityT.error(e.getMessage()); } } public static void main(String[] args) throws Exception{ //背景图片 File bgFile = FileUtils.urlToFile("https://profile.csdnimg.cn/E/9/C/1_tangcv"); //二维码地址 String path = System.getProperty("user.dir"); File qrCodeFile = new File(path + DateUtils.getDate().getTime() + ".png");//Win 服务器方式 //File qrCodeFile = new File("/sys/exam/tmp/" + DateUtils.getDate().getTime() + ".png");//Linux 服务器方式 if (!qrCodeFile.exists()) { qrCodeFile.mkdirs(); } //二维码内容 String url = "我是二维码内容"; //二维码下方文字 String words = "二维码下方文字"; BarcodeUtils.drawLogoQRCode(bgFile.getPath(),null, qrCodeFile, url, words); //上传文件阿里云 String OssUrl = OssBootUtil.upload(FileUtils.FileToMultipartFile(qrCodeFile),"QrCode"); System.out.println("二维码地址>>>>>>>>>>>" + OssUrl); // //删除临时文件 FileUtil.del(bgFile); FileUtil.del(qrCodeFile); } }

实现

 

源码地址:https://gitee.com/tangzhengfeng_admin/mybatis-plus-job-quickstart/tree/QrCode_OSS/

最新回复(0)