oss使用步骤

[复制链接]
发表于 2024-10-22 15:03:11 | 显示全部楼层 |阅读模式

1、编写配置文件 Ossconfig

package com.test1.timer.systemconfig.oss;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class OssConfig   {

    static final Logger logger = LogManager.getLogger();

    @Autowired
    SoOssConfigPojo soOssConfigPojo;
    @Autowired
    CmsOssConfigPojo cmsOssConfigPojo;

    @Bean("soAliyunTools")
    public AliyunOssTools SoAliyunUtils(){
        AliyunOssTools oss = new AliyunOssTools(soOssConfigPojo.getEndpoint(), soOssConfigPojo.getAccessKeyId(), soOssConfigPojo.getAccessKeySecret(), soOssConfigPojo.getBucketName(), soOssConfigPojo.getRootDirectory());
        return oss;
    }
    @Bean("cmsAliyunTools")
    public AliyunOssTools cmsAliyunUtils(){
        AliyunOssTools oss = new AliyunOssTools(cmsOssConfigPojo.getEndpoint(), cmsOssConfigPojo.getAccessKeyId(), cmsOssConfigPojo.getAccessKeySecret(), cmsOssConfigPojo.getBucketName(), cmsOssConfigPojo.getRootDirectory());
        return oss;
    }



    @Bean
    public TimerOssBeanPostProcessor timerOssBeanPostProcessor (){

        return new TimerOssBeanPostProcessor();
    }


}

使用

public Map<String,String> downLoadFileAndUpSeeyon(String filePath,String fileName ) {
        Map<String,String> resultMap = new HashMap<>();

        String successFlag = "0";
        String hasFileFlag = "0";
        resultMap.put("successFlag",successFlag);
        resultMap.put("hasFileFlag",hasFileFlag);
        String rootDirectory = cmsAliyunTools.getRootDirectory();
        if (StringUtils.isBlank(filePath)) {
            return resultMap;
        }

        String fileUrl = null;
        if (StringUtils.isNotBlank(rootDirectory)) {
            if (filePath.startsWith("/")) {
                fileUrl = rootDirectory + filePath;
            } else {
                fileUrl = rootDirectory + "/" + filePath;
            }
        }
        if(StringUtils.isNotBlank(fileUrl) && fileUrl.contains("//")){
            fileUrl = fileUrl.replaceAll("//","/");
        }
        File file = null;
        try {
            String localTempFileName = "/home/tempdata/" + fileUrl;
            String fileDir = localTempFileName.substring(0, localTempFileName.lastIndexOf("/"));
            File dir = new File(fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            String localTempFileNameNew =  fileDir+"/"+fileName;
            file = new File(localTempFileNameNew);
            boolean flag = cmsAliyunTools.checkIfExists(fileUrl);
            logger.info("hasFileFlag=" + flag);
            if (flag) {
                hasFileFlag = "1";
                //下载文件
                cmsAliyunTools.downloadFileByFullPath(fileUrl, file);
            }
        } catch (Exception e) {
            e.printStackTrace();

            try {
                if (file.exists()) {
                    file.delete();
                }
            } catch (Exception ex) {

            }
        }

        if (file != null && file.exists()) {
            try {
                //seeyon 文件地址
                String seeyonFileUrl = upLoadAgetSeeyonFileUrl(file);
                successFlag = "1";
                resultMap.put("seeyonFileUrl",seeyonFileUrl);
                resultMap.put("successFlag",successFlag);
                resultMap.put("hasFileFlag",hasFileFlag);
                return resultMap;
//                if(StringUtils.isNotBlank(seeyonFileUrl)){
//                    fileUrls.add(seeyonFileUrl);
//                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                if (file.exists()) {
                    file.delete();
                }
            }
        }
        return resultMap;
    }

3、工具类

package com.test1.timer.systemconfig.oss;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.DownloadFileRequest;
import com.aliyun.oss.model.DownloadFileResult;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class AliyunOssTools {
    static Logger logger = LogManager.getLogger(AliyunOssTools.class);
    private  String endpoint ;
    private  String accessKeyId  ;
    private  String accessKeySecret  ;
    private  String bucketName  ;
    private  String rootDirectory ;

    public AliyunOssTools(String endpoint, String accessKeyId, String accessKeySecret, String bucketName, String rootDirectory) {
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.bucketName = bucketName;
        this.rootDirectory = rootDirectory;
    }

    public static Logger getLogger() {
        return logger;
    }

    public static void setLogger(Logger logger) {
        AliyunOssTools.logger = logger;
    }

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    public String getRootDirectory() {
        return rootDirectory;
    }

    public void setRootDirectory(String rootDirectory) {
        this.rootDirectory = rootDirectory;
    }


    /**
     * oss文件上传
     *
     * @param filePath
     * @param fileName
     * @param inputStream
     * @throws IOException
     */
    public void ossUploadFile(String filePath, String fileName, InputStream inputStream) throws IOException {

        logger.info("ossUploadFile-filePath/fileName/iputStream={},{},{}", filePath, fileName, null);
        //获取client对象
        OSS ossClient = null;
        try {
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {

            if (!filePath.startsWith("/")) {
                filePath = "/" + filePath;
            }
            if (!filePath.endsWith("/")) {
                filePath = filePath + "/";
            }
            filePath = rootDirectory + filePath;

            String fullOssFilePathaName = filePath + fileName;
            logger.info("fullOssFilePathaName={}", fullOssFilePathaName);
            //上传文件全路径
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fullOssFilePathaName, inputStream);
            ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message:" + oe.getErrorMessage());
            logger.info("Error Code:" + oe.getErrorCode());
            logger.info("Request ID:" + oe.getRequestId());
            logger.info("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            logger.info("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.");
            logger.info("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


//    /**
//     * 下载OSS文件流
//     *
//     * @param filePath 要下载的文件名
//     */
//    public static InputStream downloadFileOfInputstream(String filePath) throws Exception {
//        // 创建OSSClient实例。
//        OSS ossClient = getOSSClient();
//        // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
//        OSSObject ossObject = ossClient.getObject(bucketName, rootDirectory + filePath);
//        return ossObject.getObjectContent();
//
//    }
//
//

    /**
     * 通过文件名下载文件
     *
     * @param
     * @param
     */
    public void downloadFile(String remotefilePath, String fileName, String saveFile) throws Exception {
        logger.info("downloadFile-remotefilePath/fileName/saveFile={},{},{}", remotefilePath, fileName, saveFile);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String objectName = null;
        try {
            if (!remotefilePath.startsWith("/")) {
                remotefilePath = "/" + remotefilePath;
            }
            if (!remotefilePath.endsWith("/")) {
                remotefilePath = remotefilePath + "/";
            }
            remotefilePath = rootDirectory + remotefilePath;
            objectName = remotefilePath + fileName;
            logger.info("downloadFile-objectName={},{},{}", remotefilePath, fileName, saveFile);
            // 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
            // 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(saveFile));
        } catch (OSSException oe) {
            logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message:" + oe.getErrorMessage());
            logger.info("Error Code:" + oe.getErrorCode());
            logger.info("Request ID:" + oe.getRequestId());
            logger.info("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            logger.info("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.");
            logger.info("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


    public void downloadFileByFullPath(String fullPath, File localSaveFile) throws Exception {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
            // 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            ossClient.getObject(new GetObjectRequest(bucketName, fullPath), localSaveFile );
        } catch (OSSException oe) {
             logger.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            logger.info("Error Message:" + oe.getErrorMessage());
            logger.info("Error Code:" + oe.getErrorCode());
            logger.info("Request ID:" + oe.getRequestId());
            logger.info("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            logger.info("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.");
            logger.info("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

    public boolean checkIfExists(String objectName){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        boolean found = ossClient.doesObjectExist(bucketName, objectName);
        //boolean found = ossClient.doesObjectExist(bucketName, objectName, isINoss);
        System.out.println(found);
        return found;
    }
    public void downloadNew(String key ,String downloadFile){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            DownloadFileRequest downloadFileRequest = new DownloadFileRequest(bucketName, key);
            // Sets the local file to download to
            downloadFileRequest.setDownloadFile(downloadFile);
            // Sets the concurrent task thread count 5. By default it's 1.
            downloadFileRequest.setTaskNum(5);
            // Sets the part size, by default it's 100K.
            downloadFileRequest.setPartSize(1024 * 1024 * 1);
            // Enable checkpoint. By default it's false.
            downloadFileRequest.setEnableCheckpoint(true);

            DownloadFileResult downloadResult = ossClient.downloadFile(downloadFileRequest);

            ObjectMetadata objectMetadata = downloadResult.getObjectMetadata();
            System.out.println(objectMetadata.getETag());
            System.out.println(objectMetadata.getLastModified());
            System.out.println(objectMetadata.getUserMetadata().get("meta"));

        } 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());
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
    }







        public static void main(String[] args) 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。
            String objectName = "testfolder/exampleobject.txt";
            // 填写Object下载到本地的完整路径。
            String pathName = "D:\\localpath\\examplefile.txt";

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

            try {
                // 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
                // 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
                ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(pathName));
            } 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();
                }
            }
        }

}

GMT+8, 2025-4-20 17:02 , Processed in 0.072382 second(s), 34 queries Archiver|手机版|小黑屋|Attic ( 京ICP备2020048627号 )

快速回复 返回顶部 返回列表