| | |
| | | import com.aliyun.oss.OSS; |
| | | import com.aliyun.oss.OSSClientBuilder; |
| | | 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 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; |
| | | |
| | | @Service |
| | |
| | | // 上传文件流 |
| | | 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 |
| | | // 第二个参数 上传到oss的文件路径和文件名称 |
| | | 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() + (long) 946080000 * 1000); |
| | | |
| | | String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString(); |
| | | |
| | | System.out.println("上传结束--" + dtf2.format(LocalDateTime.now())); |
| | | 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 { |
| | |
| | | |
| | | @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("?")); |
| | | } |
| | | try { |
| | | |
| | | fileName = URLDecoder.decode(fileName, "UTF-8"); |
| | | } catch (UnsupportedEncodingException ex) { |
| | | // throw new RuntimeException(ex); |
| | | } |
| | | |
| | | // 根据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) { |
| | | String endpoint = ConstantPropertiesUtils.END_POINT; |
| | | String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID; |
| | | String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET; |
| | | String bucketName = ConstantPropertiesUtils.BUCKET_NAME; |
| | | 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; |
| | | |
| | | // 创建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); |
| | | ObjectMetadata objectMetadata = new ObjectMetadata(); |
| | | objectMetadata.setContentType(getcontentType(ext)); |
| | | // 调用oss的方法实现长传 |
| | | // 第一个参数 bucketName |
| | | // 第二个参数 上传到oss的文件路径和文件名称 |
| | | ossClient.putObject(bucketName, fileName, inputStream, objectMetadata); |
| | | // 关闭OSSClient。 |
| | | ossClient.shutdown(); |
| | | // 把上传的文件路径返回 (手动拼接) |
| | | // 这里设置图片有效时间 我设置了30年 |
| | | Date expiration = new Date(System.currentTimeMillis() + (long) 946080000 * 1000); |
| | | String url = ossClient.generatePresignedUrl(bucketName, fileName, expiration).toString(); |
| | | System.out.println("oss上传成功:" + url); |
| | | DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); |
| | | |
| | | // 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()); |
| | | // e.printStackTrace(); |
| | | return this.uploadImages(inputStream, ext); |
| | | // 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 ""; |
| | | } |
| | | } |
| | | |
| | |
| | | } |
| | | } |
| | | |
| | | |
| | | public static String getcontentType(String FilenameExtension) { |
| | | if (FilenameExtension.equalsIgnoreCase(".mp4")||FilenameExtension.equalsIgnoreCase(".mov")) { |
| | | if (FilenameExtension.equalsIgnoreCase(".mp4") || FilenameExtension.equalsIgnoreCase(".mov")) { |
| | | return "video/mp4"; |
| | | } |
| | | if (FilenameExtension.equalsIgnoreCase(".bmp")) { |