package com.securityControl.task.util; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.OSSObject; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.util.ObjectUtils; import java.io.IOException; import java.io.InputStream; @Component public class OssUtils { @Value("${oss.endpoint}") private String endpoint; @Value("${oss.accessKeyId}") private String accessKeyId; @Value("${oss.accessKeySecret}") private String accessKeySecret; @Value("${oss.bucketName}") private String bucketName; private static byte[] lock = new byte[0]; // 位数,默认是8位 private final static long w = 100000000; public static String createID() { long r = 0; synchronized (lock) { r = (long) ((Math.random() + 1) * w); } return System.currentTimeMillis() + String.valueOf(r).substring(1); } /** * 上传图片 * * @param inputStream * @return */ public String fileUpload(InputStream inputStream) { OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); String objectName = createID(); try { ossClient.putObject(bucketName, objectName, inputStream); return objectName; } catch (Exception e) { System.err.println("文件上传失败"); e.printStackTrace(); return null; } finally { ossClient.shutdown(); } } /** * 下载图片 * * @param objectName * @return */ public byte[] getFile(String objectName) { OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); byte[] bytes = null; InputStream inputStream = null; try { OSSObject ossObject = ossClient.getObject(bucketName, objectName); inputStream = ossObject.getObjectContent(); bytes = IOUtils.toByteArray(inputStream); } catch (Exception e) { System.out.println("下载文件失败!"); e.printStackTrace(); return null; } finally { ossClient.shutdown(); if (!ObjectUtils.isEmpty(inputStream)) { try { inputStream.close(); } catch (IOException e) { System.out.println("关闭流失败!"); e.printStackTrace(); } } } return bytes; } }