依赖:
<!-- 二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>2.1</version>
</dependency>
<!-- aliyunOSS-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-mock</artifactId>
<version>2.0.8</version>
</dependency>
二维码生成工具类:
package com.jnetdata.msp.znoa.meeting.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 java.awt.image.BufferedImage; import java.util.Hashtable; /** * @Auther: pengyg * @Date: 2023/11/8 - 11 - 08 - 17:22 * @Description: com.jnetdata.msp.znoa.meeting.utils * @version: 1.0 */ public class QRCodeGenerator { private final static String CHARSET = "utf-8"; private final static int QRSIZEE = 300; // 二维码颜色 private static final int BLACK = 0xFF000000; // 二维码颜色 private static final int WHITE = 0xFFFFFFFF; public static BufferedImage createImage(String id) { String content = id; Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); hints.put(EncodeHintType.CHARACTER_SET, CHARSET); hints.put(EncodeHintType.MARGIN, 1); BitMatrix bitMatrix = null; try { bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRSIZEE, QRSIZEE, hints); } catch (Exception e) { e.printStackTrace(); } int width = bitMatrix.getWidth(); int height = bitMatrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE); } } return image; } }
控制层代码:
@ApiOperation(value = "会议申请-生成会议签到二维码") @PostMapping("/createQrCode") public JsonResult createQrCode(@RequestParam("meetingId") String meetingId){ return JsonResult.success(meetingApplyService.createQrCode(meetingId)); }
业务层代码(picture为Java自定义对象无需关注):
@Override
public String createQrCode(String meetingId) {
String urls = "";
PropertyWrapper propertyWrapper = new PropertyWrapper(Picture.class);
propertyWrapper.eq("DATAID", meetingId);
propertyWrapper.eq("TABLEID", "5");
Picture picture1 = pictureService.get(propertyWrapper);
if (!ObjectUtils.isNotEmpty(picture1)) {
LocalDate currentDate = LocalDate.now();
// 定义日期格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
// 格式化日期为字符串
String formattedDate = currentDate.format(formatter);
Picture picture = new Picture();
//核心代码生成二维码
BufferedImage image = QRCodeGenerator.createImage(meetingId);
// 创建输出流
ByteArrayOutputStream bos = null;
InputStream input=null;
// 将图像输出到输出流中。
try {
bos=new ByteArrayOutputStream();
ImageIO.write(image, "jpeg", bos);
input = new ByteArrayInputStream(bos.toByteArray());
MultipartFile multipartFile = new MockMultipartFile(meetingId, meetingId + ".jpeg", "", input);
String filename = "znoa/meeting/" + formattedDate + "/" + UUID.randomUUID().toString().replace("-", "") + "/" + meetingId + ".jpeg";
urls = updateHead(multipartFile,filename);
picture.setPath(urls);
picture.setUrl(urls);
picture.setDataId(meetingId);
picture.setTableid("5");
pictureService.insert(picture);
} catch (Exception e) {
throw new RuntimeException(e);
}finally {
if (null!=input) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null!=bos){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else{
urls=picture1.getPath();
}
return urls;
}
private String updateHead(MultipartFile file,String filename) throws Exception {
if (file == null || file.getSize() <= 0) {
throw new Exception("file不能为空");
}
return aliyunOssFileUtil.upload(file, filename);
}
OSS工具类:
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.jnetdata.msp.resources.util.aliyunoss;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CopyObjectResult;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Resource;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Component
public class AliyunOssFileUtil {
@Resource
private OSSProperties ossProperties;
public AliyunOssFileUtil() {
}
public String getContentType(String FilenameExtension) {
if (FilenameExtension.equalsIgnoreCase(".bmp")) {
return "image/bmp";
} else if (FilenameExtension.equalsIgnoreCase(".gif")) {
return "image/gif";
} else if (!FilenameExtension.equalsIgnoreCase(".jpeg") && !FilenameExtension.equalsIgnoreCase(".jpg") && !FilenameExtension.equalsIgnoreCase(".png")) {
if (FilenameExtension.equalsIgnoreCase(".html")) {
return "text/html";
} else if (FilenameExtension.equalsIgnoreCase(".txt")) {
return "text/plain";
} else if (FilenameExtension.equalsIgnoreCase(".vsd")) {
return "application/vnd.visio";
} else if (!FilenameExtension.equalsIgnoreCase(".pptx") && !FilenameExtension.equalsIgnoreCase(".ppt")) {
if (!FilenameExtension.equalsIgnoreCase(".docx") && !FilenameExtension.equalsIgnoreCase(".doc")) {
if (FilenameExtension.equalsIgnoreCase(".pdf")) {
return "application/pdf";
} else if (FilenameExtension.equalsIgnoreCase(".zip")) {
return "application/zip";
} else if (!FilenameExtension.equalsIgnoreCase(".xls") && !FilenameExtension.equalsIgnoreCase(".xlsx")) {
return FilenameExtension.equalsIgnoreCase(".xml") ? "text/xml" : "application/octet-stream";
} else {
return "application/vnd.ms-excel";
}
} else {
return "application/msword";
}
} else {
return "application/vnd.ms-powerpoint";
}
} else {
return "image/jpg";
}
}
public String upload(MultipartFile multipartFile, String fileUrl) {
String endpoint = this.ossProperties.getEndPoint();
String accessKeyId = this.ossProperties.getAccessKeyId();
String accessKeySecret = this.ossProperties.getAccessKeySecret();
String bucketName = this.ossProperties.getBucketName();
String fileName = multipartFile.getOriginalFilename();
OSS ossClient = (new OSSClientBuilder()).build(endpoint, accessKeyId, accessKeySecret);
try {
if (!ossClient.doesBucketExist(bucketName)) {
ossClient.createBucket(bucketName);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
createBucketRequest.setCannedACL(CannedAccessControlList.Private);
ossClient.createBucket(createBucketRequest);
}
ObjectMetadata objectMetadata = new ObjectMetadata();
String type = this.getContentType(fileName.substring(fileName.lastIndexOf(46)));
objectMetadata.setContentType(type);
objectMetadata.setObjectAcl(CannedAccessControlList.Default);
PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, multipartFile.getInputStream(), objectMetadata));
System.out.println(result.toString());
if (result != null) {
System.out.println("==========>OSS文件上传成功,OSS地址:" + fileUrl);
}
} catch (OSSException var16) {
System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
System.out.println("Error Message:" + var16.getErrorMessage());
System.out.println("Error Code:" + var16.getErrorCode());
System.out.println("Request ID:" + var16.getRequestId());
System.out.println("Host ID:" + var16.getHostId());
} catch (Exception var17) {
throw new RuntimeException(var17);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return fileUrl;
}
public String uploadDocFile(MultipartFile multipartFile, String fileUrl) throws FileNotFoundException {
String bucketName = this.ossProperties.getBucketName();
String endpoint = this.ossProperties.getEndPoint();
String accessKeyId = this.ossProperties.getAccessKeyId();
String accessKeySecret = this.ossProperties.getAccessKeySecret();
Map<String, String> headers = new HashMap();
Map<String, String> userMetadata = new HashMap();
URL signedUrl = null;
OSS ossClient = (new OSSClientBuilder()).build(endpoint, accessKeyId, accessKeySecret);
String url;
try {
url = multipartFile.getOriginalFilename();
ObjectMetadata objectMetadata = new ObjectMetadata();
String type = this.getContentType(url.substring(url.lastIndexOf(46)));
objectMetadata.setContentType(type);
objectMetadata.setObjectAcl(CannedAccessControlList.Default);
fileUrl = fileUrl + "/" + url;
PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, multipartFile.getInputStream(), objectMetadata));
System.out.println(result.toString());
if (result != null) {
System.out.println("==========>OSS文件上传成功,OSS地址:" + fileUrl);
}
Date expiration = new Date((new Date()).getTime() + 86400000L);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileUrl, HttpMethod.GET);
request.setExpiration(expiration);
request.setHeaders(headers);
request.setUserMetadata(userMetadata);
signedUrl = ossClient.generatePresignedUrl(request);
System.out.println("signed url for putObject: " + signedUrl);
} catch (OSSException var21) {
System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
System.out.println("Error Message:" + var21.getErrorMessage());
System.out.println("Error Code:" + var21.getErrorCode());
System.out.println("Request ID:" + var21.getRequestId());
System.out.println("Host ID:" + var21.getHostId());
} catch (Exception var22) {
throw new RuntimeException(var22);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
url = signedUrl.toString();
return url;
}
public void deleteBlog(String deleteUrl) {
String endpoint = this.ossProperties.getEndPoint();
String accessKeyId = this.ossProperties.getAccessKeyId();
String accessKeySecret = this.ossProperties.getAccessKeySecret();
String bucketName = this.ossProperties.getBucketName();
String objectName = deleteUrl;
OSS ossClient = (new OSSClientBuilder()).build(endpoint, accessKeyId, accessKeySecret);
try {
ossClient.deleteObject(bucketName, objectName);
} catch (OSSException var12) {
System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
System.out.println("Error Message:" + var12.getErrorMessage());
System.out.println("Error Code:" + var12.getErrorCode());
System.out.println("Request ID:" + var12.getRequestId());
System.out.println("Host ID:" + var12.getHostId());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
public String copyFile(String fromUrl, String toUrl) {
String bucketName = this.ossProperties.getBucketName();
String endPoint = this.ossProperties.getEndPoint();
String accessKeyId = this.ossProperties.getAccessKeyId();
String accessKeySecret = this.ossProperties.getAccessKeySecret();
String sourceBucketName = bucketName;
String sourceKey = fromUrl;
String destinationBucketName = bucketName;
String destinationKey = toUrl;
Map<String, String> headers = new HashMap();
Map<String, String> userMetadata = new HashMap();
URL signedUrl = null;
OSS ossClient = (new OSSClientBuilder()).build(endPoint, accessKeyId, accessKeySecret);
try {
CopyObjectResult result = ossClient.copyObject(sourceBucketName, sourceKey, destinationBucketName, destinationKey);
System.out.println("ETag: " + result.getETag() + " LastModified: " + result.getLastModified());
Date expiration = new Date((new Date()).getTime() + 86400000L);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, toUrl, HttpMethod.GET);
request.setExpiration(expiration);
request.setHeaders(headers);
request.setUserMetadata(userMetadata);
signedUrl = ossClient.generatePresignedUrl(request);
System.out.println("signed url for putObject: " + signedUrl);
} catch (OSSException var22) {
System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
System.out.println("Error Message:" + var22.getErrorMessage());
System.out.println("Error Code:" + var22.getErrorCode());
System.out.println("Request ID:" + var22.getRequestId());
System.out.println("Host ID:" + var22.getHostId());
} catch (ClientException var23) {
System.out.println("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
System.out.println("Error Message:" + var23.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return signedUrl.toString();
}
public String download(String objectName) {
String endpoint = this.ossProperties.getEndPoint();
String accessKeyId = this.ossProperties.getAccessKeyId();
String accessKeySecret = this.ossProperties.getAccessKeySecret();
String bucketName = this.ossProperties.getBucketName();
OSS ossClient = (new OSSClientBuilder()).build(endpoint, accessKeyId, accessKeySecret);
Map<String, String> headers = new HashMap();
Map<String, String> userMetadata = new HashMap();
URL signedUrl = null;
try {
Date expiration = new Date((new Date()).getTime() + 3600000L);
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
request.setExpiration(expiration);
request.setHeaders(headers);
request.setUserMetadata(userMetadata);
signedUrl = ossClient.generatePresignedUrl(request);
System.out.println("signed url for putObject: " + signedUrl);
} catch (OSSException var12) {
System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
System.out.println("Error Message:" + var12.getErrorMessage());
System.out.println("Error Code:" + var12.getErrorCode());
System.out.println("Request ID:" + var12.getRequestId());
System.out.println("Host ID:" + var12.getHostId());
} catch (ClientException var13) {
System.out.println("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
System.out.println("Error Message:" + var13.getMessage());
}
assert signedUrl != null;
return signedUrl.toString();
}
public void getObjectWithHttp(URL signedUrl, String pathName, Map<String, String> headers, Map<String, String> userMetadata) throws IOException {
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
try {
HttpGet get = new HttpGet(signedUrl.toString());
Iterator var8 = headers.entrySet().iterator();
Entry meta;
while(var8.hasNext()) {
meta = (Entry)var8.next();
get.addHeader(meta.getKey().toString(), meta.getValue().toString());
}
var8 = userMetadata.entrySet().iterator();
while(var8.hasNext()) {
meta = (Entry)var8.next();
get.addHeader("x-oss-meta-" + meta.getKey().toString(), meta.getValue().toString());
}
httpClient = HttpClients.createDefault();
response = httpClient.execute(get);
System.out.println("返回下载状态码:" + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 200) {
System.out.println("使用网络库下载成功");
}
System.out.println(response.toString());
saveFileToLocally(response.getEntity().getContent(), pathName);
} catch (Exception var13) {
var13.printStackTrace();
} finally {
response.close();
httpClient.close();
}
}
public void createDir(String objectName) {
String bucketName = this.ossProperties.getBucketName();
String endpoint = this.ossProperties.getEndPoint();
String accessKeyId = this.ossProperties.getAccessKeyId();
String accessKeySecret = this.ossProperties.getAccessKeySecret();
OSS ossClient = (new OSSClientBuilder()).build(endpoint, accessKeyId, accessKeySecret);
try {
String content = "";
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
ossClient.putObject(putObjectRequest);
} catch (OSSException var13) {
System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
System.out.println("Error Message:" + var13.getErrorMessage());
System.out.println("Error Code:" + var13.getErrorCode());
System.out.println("Request ID:" + var13.getRequestId());
System.out.println("Host ID:" + var13.getHostId());
} catch (ClientException var14) {
System.out.println("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
System.out.println("Error Message:" + var14.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
public void deleteDir(String prefix) {
String bucketName = this.ossProperties.getBucketName();
String endpoint = this.ossProperties.getEndPoint();
String accessKeyId = this.ossProperties.getAccessKeyId();
String accessKeySecret = this.ossProperties.getAccessKeySecret();
OSS ossClient = (new OSSClientBuilder()).build(endpoint, accessKeyId, accessKeySecret);
try {
String nextMarker = null;
ObjectListing objectListing = null;
do {
ListObjectsRequest listObjectsRequest = (new ListObjectsRequest(bucketName)).withPrefix(prefix).withMarker(nextMarker);
objectListing = ossClient.listObjects(listObjectsRequest);
if (objectListing.getObjectSummaries().size() > 0) {
List<String> keys = new ArrayList();
Iterator var11 = objectListing.getObjectSummaries().iterator();
while(var11.hasNext()) {
OSSObjectSummary s = (OSSObjectSummary)var11.next();
System.out.println("key name: " + s.getKey());
keys.add(s.getKey());
}
DeleteObjectsRequest deleteObjectsRequest = (new DeleteObjectsRequest(bucketName)).withKeys(keys).withEncodingType("url");
DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(deleteObjectsRequest);
List deletedObjects = deleteObjectsResult.getDeletedObjects();
try {
Iterator var14 = deletedObjects.iterator();
while(var14.hasNext()) {
String obj = (String)var14.next();
String deleteObj = URLDecoder.decode(obj, "UTF-8");
System.out.println(deleteObj);
}
} catch (UnsupportedEncodingException var22) {
var22.printStackTrace();
}
}
nextMarker = objectListing.getNextMarker();
} while(objectListing.isTruncated());
} catch (OSSException var23) {
System.out.println("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
System.out.println("Error Message:" + var23.getErrorMessage());
System.out.println("Error Code:" + var23.getErrorCode());
System.out.println("Request ID:" + var23.getRequestId());
System.out.println("Host ID:" + var23.getHostId());
} catch (ClientException var24) {
System.out.println("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
System.out.println("Error Message:" + var24.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
public static void saveFileToLocally(InputStream inputStream, String pathName) throws IOException {
DataInputStream in = null;
DataOutputStream out = null;
try {
in = new DataInputStream(inputStream);
out = new DataOutputStream(new FileOutputStream(pathName));
int bytes = false;
byte[] bufferOut = new byte[1024];
int bytes;
while((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
} catch (Exception var9) {
var9.printStackTrace();
} finally {
in.close();
out.close();
}
}
}
下载二维码:
public String download(String objectName) { String endpoint = ossConstantProperties.getEndPoint(); String accessKeyId = ossConstantProperties.getAccessKeyId(); String accessKeySecret = ossConstantProperties.getAccessKeySecret(); String bucketName = ossConstantProperties.getBucketName(); // 从STS服务获取临时访问凭证后,您可以通过临时访问密钥和安全令牌生成OSSClient(既这里的accessKeyId和accessKeySecret为STS服务返回的)。 // 使用STS创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 设置请求头。 Map<String, String> headers = new HashMap<String, String>(); // 设置用户自定义元信息。 Map<String, String> userMetadata = new HashMap<String, String>(); URL signedUrl = null; try { // 指定生成的签名URL过期时间,单位为毫秒。 Date expiration = new Date(new Date().getTime() + 3600 * 1000); // 生成签名URL。 GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET); // 设置过期时间。 request.setExpiration(expiration); // 将请求头加入到request中。 request.setHeaders(headers); // 添加用户自定义元信息。 request.setUserMetadata(userMetadata); // 通过HTTP GET请求生成签名URL。 signedUrl = ossClient.generatePresignedUrl(request); // 打印签名URL。 System.out.println("signed url for putObject: " + signedUrl); } catch (OSSException oe) { System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason."); System.out.println("Error Message:" + oe.getErrorMessage()); System.out.println("Error Code:" + oe.getErrorCode()); System.out.println("Request ID:" + oe.getRequestId()); System.out.println("Host ID:" + oe.getHostId()); } catch (ClientException ce) { System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network."); System.out.println("Error Message:" + ce.getMessage()); } assert signedUrl != null; return signedUrl.toString(); // 通过签名URL下载文件,以HttpClients为例说明。 // getObjectWithHttp(signedUrl, pathName, headers, userMetadata); }