Java 封装阿里云 oss 上传图片时抽取配置到 application 使用 @Value 获取值
package com.zhong.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.InputStream;
/**
* @ClassName : AliOssUtil
* @Description : 阿里云上传服务
* @Author : zhx
* @Date: 2024-03-1 20:29
*/
@Component
public class AliOssUtil {
// 抽取配置
private static String ENDPOINT;
@Value("${alioss.endpoint}")
public void setENDPOINT(String endpoint){
ENDPOINT = endpoint;
}
private static String ACCESS_KEY;
@Value("${alioss.access_key}")
public void setAccessKey(String accessKey){
ACCESS_KEY = accessKey;
}
private static String ACCESS_KEY_SECRET;
@Value("${alioss.access_key_secret}")
public void setAccessKeySecret(String accessKeySecret){
ACCESS_KEY_SECRET = accessKeySecret;
}
private static String BUCKETNAME;
@Value("${alioss.bucketName}")
public void setBUCKETNAME(String bucketName){
BUCKETNAME = bucketName;
}
// 上传业务
public static String uploadFile(String objectName, InputStream inputStream) {
String url = "";
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY, ACCESS_KEY_SECRET);
try {
// 创建PutObjectRequest对象。
PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, objectName, inputStream);
// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);
// 上传文件。
PutObjectResult result = ossClient.putObject(putObjectRequest);
url = "https://" + BUCKETNAME + "." + ENDPOINT.substring(ENDPOINT.lastIndexOf("/") + 1) + "/" + objectName;
} 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();
}
}
return url;
}
}