From 1cad14bca191807e18705c3a5526eda8151be439 Mon Sep 17 00:00:00 2001 From: zhanghua <314079846@qq.com> Date: 星期一, 14 四月 2025 23:10:22 +0800 Subject: [PATCH] 批量审核和图片保存bug --- ycl-common/src/main/java/com/ycl/service/oss/impl/OssServiceImpl.java | 224 ++++++++++++++++++++++++++++++++++++++++++++----------- 1 files changed, 178 insertions(+), 46 deletions(-) diff --git a/ycl-common/src/main/java/com/ycl/service/oss/impl/OssServiceImpl.java b/ycl-common/src/main/java/com/ycl/service/oss/impl/OssServiceImpl.java index 6d3e490..3cae4d0 100644 --- a/ycl-common/src/main/java/com/ycl/service/oss/impl/OssServiceImpl.java +++ b/ycl-common/src/main/java/com/ycl/service/oss/impl/OssServiceImpl.java @@ -1,31 +1,41 @@ package com.ycl.service.oss.impl; -import com.aliyun.oss.ClientBuilderConfiguration; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; -import com.aliyun.oss.common.comm.Protocol; import com.aliyun.oss.model.ObjectMetadata; +import com.aliyun.oss.model.VoidResult; import com.ycl.service.oss.OssService; import com.ycl.utils.ConstantPropertiesUtils; import com.ycl.utils.common.RandomUtils; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.InputStream; -import java.net.HttpURLConnection; +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.stream.ImageOutputStream; +import java.awt.*; +import java.awt.image.BufferedImage; +import java.io.*; import java.net.URL; +import java.net.URLDecoder; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; +import java.util.Arrays; import java.util.Date; -import java.util.UUID; @Service public class OssServiceImpl implements OssService { @Override public String uploadImages(MultipartFile file) { + DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + System.out.println("寮�濮嬩笂浼�--" + dtf2.format(LocalDateTime.now())); + if (file == null) { + return "涓婁紶鏂囦欢涓虹┖"; + } String endpoint = ConstantPropertiesUtils.END_POINT; String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID; String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET; @@ -36,26 +46,94 @@ // 涓婁紶鏂囦欢娴� try { // 鑾峰彇鏂囦欢鐨勫悕绉� - String fileName = "sczf/" + file.getOriginalFilename(); + + byte[] newImg = file.getBytes(); + String originalFilename = file.getOriginalFilename(); + String fileType = originalFilename.substring(originalFilename.lastIndexOf(".")); + + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); + String fileName = "sczf/" + LocalDateTime.now().format(formatter) + RandomUtils.generateRandomInt(8) + fileType; + + if (".png".equalsIgnoreCase(fileType) || ".jpg".equalsIgnoreCase(fileType) || ".jpeg".equalsIgnoreCase(fileType)) { + if (file.getSize() > 2097152) { + newImg = compressUnderSize(file.getBytes(), 2097152); + } + } ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf(".")))); // 璋冪敤oss鐨勬柟娉曞疄鐜伴暱浼� // 绗竴涓弬鏁� bucketName // 绗簩涓弬鏁� 涓婁紶鍒皁ss鐨勬枃浠惰矾寰勫拰鏂囦欢鍚嶇О - ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(file.getBytes()), objectMetadata); + ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(newImg), objectMetadata); // 鍏抽棴OSSClient銆� ossClient.shutdown(); // 鎶婁笂浼犵殑鏂囦欢璺緞杩斿洖 锛堟墜鍔ㄦ嫾鎺ワ級 // 杩欓噷璁剧疆鍥剧墖鏈夋晥鏃堕棿 鎴戣缃簡30骞� - Date expiration = new Date(System.currentTimeMillis() + 946080000 * 1000); + Date expiration = new Date(System.currentTimeMillis() + (long) 946080000 * 1000); + String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString(); + System.out.println("涓婁紶缁撴潫--" + url + "------" + dtf2.format(LocalDateTime.now())); return url; } catch (Exception e) { System.out.println("uploadImages涓婁紶鍥剧墖澶辫触锛�"); // e.printStackTrace(); return null; } + } + + /** + * 鎸夌収 瀹介珮 姣斾緥鍘嬬缉 + * + * @param imgIs 寰呭帇缂╁浘鐗囪緭鍏ユ祦 + * @param scale 鍘嬬缉鍒诲害 + * @param out 杈撳嚭 + * @return 鍘嬬缉鍚庡浘鐗囨暟鎹� + * @throws IOException 鍘嬬缉鍥剧墖杩囩▼涓嚭閿� + */ + public byte[] compress(byte[] srcImgData, double scale) throws IOException { + BufferedImage bi = ImageIO.read(new ByteArrayInputStream(srcImgData)); + int width = (int) (bi.getWidth() * scale); // 婧愬浘瀹藉害 + int height = (int) (bi.getHeight() * scale); // 婧愬浘楂樺害 + + Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH); + BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + + Graphics g = tag.getGraphics(); + g.setColor(Color.RED); + g.drawImage(image, 0, 0, null); // 缁樺埗澶勭悊鍚庣殑鍥� + g.dispose(); + + ByteArrayOutputStream bOut = new ByteArrayOutputStream(); + ImageIO.write(tag, "JPEG", bOut); + + return bOut.toByteArray(); + } + + /** + * 灏嗗浘鐗囧帇缂╁埌鎸囧畾澶у皬浠ュ唴 + * + * @param srcImgData 婧愬浘鐗囨暟鎹� + * @param maxSize 鐩殑鍥剧墖澶у皬 + * @return 鍘嬬缉鍚庣殑鍥剧墖鏁版嵁 + */ + public byte[] compressUnderSize(byte[] srcImgData, long maxSize) { + double scale = 0.9; + byte[] imgData = Arrays.copyOf(srcImgData, srcImgData.length); + + if (imgData.length > maxSize) { + do { + try { + imgData = compress(imgData, scale); + + } catch (IOException e) { + throw new IllegalStateException("鍘嬬缉鍥剧墖杩囩▼涓嚭閿欙紝璇峰強鏃惰仈绯荤鐞嗗憳锛�", e); + } + + } while (imgData.length > maxSize); + } + + return imgData; } private byte[] readInputStream(InputStream inStream) throws Exception { @@ -77,71 +155,125 @@ @Override public boolean deleteImages(String fileUrl) { - String endpoint = ConstantPropertiesUtils.END_POINT; - String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID; - String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET; - String bucketName = ConstantPropertiesUtils.BUCKET_NAME; - //鍒涘缓OSSClient瀹炰緥 - OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); - String imgFile = fileUrl.replace("https://bucket-ans.oss-cn-hangzhou.aliyuncs.com/", ""); - String fileName = imgFile.substring(0, imgFile.indexOf("?")); + try { - // 鏍规嵁BucketName,objectName鍒犻櫎鏂囦欢 - ossClient.deleteObject(bucketName, fileName); - ossClient.shutdown(); - return true; + String endpoint = ConstantPropertiesUtils.END_POINT; + String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID; + String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET; + String bucketName = ConstantPropertiesUtils.BUCKET_NAME; + //鍒涘缓OSSClient瀹炰緥 + OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); + + String imgFile = fileUrl.replace(ConstantPropertiesUtils.PREFIX_URL, ""); + String fileName = imgFile; + if (imgFile.contains("?")) { + fileName = imgFile.substring(0, imgFile.indexOf("?")); + } + + fileName = URLDecoder.decode(fileName, "UTF-8"); + + // 鏍规嵁BucketName,objectName鍒犻櫎鏂囦欢 + boolean b = ossClient.doesObjectExist(bucketName, fileName); + if (b) { + VoidResult voidResult = ossClient.deleteObject(bucketName, fileName); +// System.out.println(voidResult.toString()); + } + ossClient.shutdown(); + return true; + + } catch (Exception e) { + System.out.println("-------鍒犻櫎鍥剧墖澶辫触锛屽浘鐗囧湴鍧�:" + fileUrl); + } + return false; } @Override - public String uploadImages(InputStream inputStream, String ext) { + public String uploadImages(InputStream inputStream, String ext, Integer times) { + if (times < 3) { + String endpoint = ConstantPropertiesUtils.END_POINT; + String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID; + String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET; + String bucketName = ConstantPropertiesUtils.BUCKET_NAME; + + DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + +// System.out.println("鍑嗗涓婁紶--" + dtf2.format(LocalDateTime.now())); + // 鍒涘缓OSSClient瀹炰緥銆� + OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); + // 涓婁紶鏂囦欢娴� + try { + // 鑾峰彇鏂囦欢鐨勫悕绉� + LocalDate date = LocalDate.now(); + DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); + String fileName = "sczf/" + date.format(formatter) + RandomUtils.generateRandomInt(8) + ext; + + ObjectMetadata objectMetadata = new ObjectMetadata(); + objectMetadata.setContentType(getcontentType(ext)); + +// System.out.println("寮�濮嬩笂浼�--" + dtf2.format(LocalDateTime.now())); + + ossClient.putObject(bucketName, fileName, inputStream, objectMetadata); + ossClient.shutdown(); + + Date expiration = new Date(System.currentTimeMillis() + (long) 946080000 * 1000); + + String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString(); +// System.out.println("oss涓婁紶鎴愬姛锛�" + url); + +// System.out.println("涓婁紶瀹屾垚--" + dtf2.format(LocalDateTime.now())); + return url; + + } catch (Exception e) { + System.out.println("oss寮傚父锛�" + e.getMessage()); + // e.printStackTrace(); + return this.uploadImages(inputStream, ext, times + 1); + } + } else { + return ""; + } + } + + @Override + public String uploadVideo(MultipartFile file) { + if (file == null) { + return "涓婁紶瑙嗛涓虹┖"; + } String endpoint = ConstantPropertiesUtils.END_POINT; String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID; String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET; String bucketName = ConstantPropertiesUtils.BUCKET_NAME; - - // 鍒涘缓OSSClient瀹炰緥銆� + // 鍒涘缓OSSClient瀹炰緥 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); // 涓婁紶鏂囦欢娴� try { // 鑾峰彇鏂囦欢鐨勫悕绉� - LocalDate date = LocalDate.now(); - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd"); - String fileName = "sczf/" + date.format(formatter) + RandomUtils.generateRandomInt(8) + "." + ext; - System.out.println("鏂囦欢鍦板潃锛�" + fileName); + String fileName = "sczf/" + file.getOriginalFilename(); ObjectMetadata objectMetadata = new ObjectMetadata(); - objectMetadata.setContentType(getcontentType(ext)); + objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf(".")))); // 璋冪敤oss鐨勬柟娉曞疄鐜伴暱浼� // 绗竴涓弬鏁� bucketName // 绗簩涓弬鏁� 涓婁紶鍒皁ss鐨勬枃浠惰矾寰勫拰鏂囦欢鍚嶇О - ossClient.putObject(bucketName, fileName, inputStream, objectMetadata); + ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(file.getBytes()), objectMetadata); // 鍏抽棴OSSClient銆� ossClient.shutdown(); // 鎶婁笂浼犵殑鏂囦欢璺緞杩斿洖 锛堟墜鍔ㄦ嫾鎺ワ級 // 杩欓噷璁剧疆鍥剧墖鏈夋晥鏃堕棿 鎴戣缃簡30骞� - Date expiration = new Date(System.currentTimeMillis() + 946080000 * 1000); + Date expiration = new Date(System.currentTimeMillis() + (long) 946080000 * 1000); String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString(); - System.out.println("oss涓婁紶鎴愬姛锛�" + url); - URL urlO = new URL(url); - HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); - conn.setRequestMethod("GET"); - conn.setConnectTimeout(10 * 1000); - conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); - - InputStream inputStream2 = conn.getInputStream();// 閫氳繃杈撳叆娴佽幏鍙栧浘鐗囨暟鎹� - - byte[] data = readInputStream(inputStream2); - - System.out.println("鑾峰彇鍥剧墖鎴愬姛:" + url); return url; } catch (Exception e) { - System.out.println("oss寮傚父锛�" + e.getMessage()); + System.out.println("uploadImages涓婁紶瑙嗛澶辫触锛�"); // e.printStackTrace(); - return this.uploadImages(inputStream, ext); + return null; } } + public static String getcontentType(String FilenameExtension) { + if (FilenameExtension.equalsIgnoreCase(".mp4") || FilenameExtension.equalsIgnoreCase(".mov")) { + return "video/mp4"; + } if (FilenameExtension.equalsIgnoreCase(".bmp")) { return "image/bmp"; } -- Gitblit v1.8.0