package com.ycl.utils; import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.InputStream; import java.util.UUID; @Component public class AliyunUtils { private static String endpoint; private static String keyId; private static String keySecret; private static String bucketName; @Value("${aliyun.oss.endpoint}") public void setEndpoint(String endpoint) { AliyunUtils.endpoint = endpoint; } @Value("${aliyun.oss.keyId}") public void setKeyId(String keyId) { AliyunUtils.keyId = keyId; } @Value("${aliyun.oss.keySecret}") public void setKeySecret(String keySecret) { AliyunUtils.keySecret = keySecret; } @Value("${aliyun.oss.bucketName}") public void setBucketName(String bucketName) { AliyunUtils.bucketName = bucketName; } public static String upload(InputStream inputStream, String orginalFileName){ // 创建OSSClient实例。 OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret); // 文件名 String fileName = UUID.randomUUID().toString(); //文件扩展名 String fileExtention = orginalFileName.substring(orginalFileName.lastIndexOf(".")); //最终的路径 类似avatar/2021/12/05/xxxxxxxxx.jpg String objectName = fileName+fileExtention; ossClient.putObject(bucketName, objectName, inputStream); // 关闭OSSClient。 ossClient.shutdown(); return "https://"+bucketName+"."+endpoint+"/"+objectName; } public static void delete(String link){ if (link == null || link.equals("")) { return; } OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret); try { ossClient.deleteObject(bucketName, link); } 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()); } finally { if (ossClient != null) { ossClient.shutdown(); } } } }