package tqq9.lc123.cloud.app.fileserver; import com.aliyun.oss.*; import com.aliyun.oss.common.auth.CredentialsProviderFactory; import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult; import kd.bos.filestorage.s3.util.URLUtils; import kd.bos.filestorage.spi.FileStorageConfig; import kd.bos.filestorage.spi.FileStorageService; import kd.bos.logging.Log; import kd.bos.logging.LogFactory; import tqq9.lc123.cloud.app.plugin.utils.ConfigUtils; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import java.util.Map; /** * 阿里云OSS文件服务扩展 */ public class OSSFileStorageServiceExt implements FileStorageService { private static final Log log = LogFactory.getLog(OSSFileStorageServiceExt.class); private OSS ossClient; private String endPoint = ConfigUtils.getThirdConfigByNumber("ALI_OSS_EndPoint"); private String accessKeyId = ConfigUtils.getThirdConfigByNumber("ALI_OSS_AccessKey_ID"); private String accessKeySecret = ConfigUtils.getThirdConfigByNumber("ALI_OSS_AccessKey_Secret"); //目录名称 private String directory = ConfigUtils.getThirdConfigByNumber("ALI_OSS_Directory"); //存储空间名称 private String bucketName = ConfigUtils.getThirdConfigByNumber("ALI_OSS_BucketName"); //地域 private String region = ConfigUtils.getThirdConfigByNumber("ALI_OSS_Region"); @Override public void setConfig(FileStorageConfig fileStorageConfig) { ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret); } @Override public List getForbiddenExtensions() throws Exception { return null; } @Override public String getTicket() throws Exception { return null; } @Override public String upload(InputStream inputStream, String filePath, String fileName, boolean isCreateNewFileWhenExists, Map headers) throws Exception { // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 //String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填写Bucket名称,例如examplebucket。 // String bucketName = "examplebucket"; // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。 String objectName = directory + "/" + fileName; // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。 // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。 // String filePath= "D:\\localpath\\examplefile.txt"; // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。 // String region = "cn-hangzhou"; // 创建OSSClient实例。 // 当OSSClient实例不再使用时,调用shutdown方法以释放资源。 ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endPoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // 创建PutObjectRequest对象。 PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath)); // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。 // 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); } 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 null; } @Override public InputStream getInputStream(String fullFilePath, String userAgent) throws Exception { URLUtils.ValidUrl validUrl = URLUtils.getValidUrl(fullFilePath); return ossClient.getObject(bucketName, validUrl.getFilePath()).getObjectContent(); } @Override public void download(String fullFilePath, OutputStream outputStream, String userAgent) throws Exception { // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 // String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; //从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填写Bucket名称,例如examplebucket。 // String bucketName = "examplebucket"; // 填写不包含Bucket名称在内的Object完整路径,例如testfolder/exampleobject.txt。 File file = new File(fullFilePath); String fileName = file.getName(); String objectName = directory + "/" + fileName; // 填写Object下载到本地的完整路径。 // String pathName = "D:\\localpath\\examplefile.txt"; // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。 // String region = "cn-hangzhou"; // 创建OSSClient实例。 // 当OSSClient实例不再使用时,调用shutdown方法以释放资源。 ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endPoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。 // 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。 // ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(fullFilePath)); } 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(); } } } @Override public void delete(String fullFilePath) throws Exception { // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 // String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填写Bucket名称,例如examplebucket。 // String bucketName = "examplebucket"; // 填写文件完整路径。文件完整路径中不能包含Bucket名称。 // String objectName = "exampleobject.txt"; File file = new File(fullFilePath); String objectName = file.getName(); // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。 // String region = "cn-hangzhou"; // 创建OSSClient实例。 // 当OSSClient实例不再使用时,调用shutdown方法以释放资源。 ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endPoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // 删除文件或目录。如果要删除目录,目录必须为空。 ossClient.deleteObject(bucketName, 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(); } } } @Override public boolean exists(String fullFilePath) throws Exception { // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。 // String endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider(); // 填写Bucket名称,例如examplebucket。 // String bucketName = "examplebucket"; // 填写不包含Bucket名称在内的Object完整路径,例如exampleobject.txt。 // String objectName = "exampleobject.txt"; File file = new File(fullFilePath); String objectName = file.getName(); // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。 // String region = "cn-hangzhou"; // 创建OSSClient实例。 // 当OSSClient实例不再使用时,调用shutdown方法以释放资源。 ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endPoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // 判断文件是否存在。如果返回值为true,则文件存在,否则存储空间或者文件不存在。 // 设置是否进行重定向或者镜像回源。默认值为true,表示忽略302重定向和镜像回源;如果设置isINoss为false,则进行302重定向或者镜像回源。 //boolean isINoss = true; boolean found = ossClient.doesObjectExist(bucketName, objectName); //boolean found = ossClient.doesObjectExist(bucketName, objectName, isINoss); System.out.println(found); } 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 false; } @Override public void close() throws IOException { if(ossClient != null){ ossClient.shutdown(); } } }