package com.ruoyi.common.utils.aliyunoss;


import com.alibaba.fastjson2.JSONObject;
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.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.StorageClass;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.UUIDUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class OssUtil {

    public static void main(String[] angs){
        JSONObject map = new JSONObject();
        map.put("domain","oss-cn-zhangjiakou.aliyuncs.com");//不同区域上传域名是不同的
        map.put("bucketName","ceshi");//桶名称
        map.put("accessKeyId","123");
        map.put("accessKeySecret","123");
        map.put("filePath","C:\\Users\\86186\\Desktop\\sql\\新建文件夹\\测试.zip");//本地文件所在路径
                
        map.put("bindDomain","http://域名/");
        //上传文件
        fileLocalUpload(map);
        
        //删除时OSS文件url
        map.put("imgUrl","http://域名/sdfg/dfg/dfg/99aa2fc3430f.png");
        fileDelete(map);
    }

    static Map<String,String> getFilePath(String type){
        Map<String,String> map = new HashMap<>();
        map.put("mp4","pdd_video");
        map.put("avi","pdd_video");
        map.put("wmv","pdd_video");
        map.put("mpg","pdd_video");
        map.put("mpeg","pdd_video");
        map.put("mov","pdd_video");
        map.put("rm","pdd_video");
        map.put("ram","pdd_video");
        map.put("swf","pdd_video");
        map.put("flv","pdd_video");
        map.put("ram","pdd_video");
        return map;
    }

    //上传文件
    public static String fileUpload(JSONObject json) {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String http = "https://";
        String endpoint = json.getString("domain");//"oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = json.getString("accessKeyId");//"LT";
        String accessKeySecret = json.getString("accessKeySecret");//"ui2oVSG";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = json.getString("bucketName");//"";
        String bindDomain = json.getString("bindDomain");//绑定的域名

        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        MultipartFile file = (MultipartFile)json.get("file");

        //获取原文件名
        String fileName = file.getOriginalFilename();
        //获取文件后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));

        String imgPath = json.getString("imgPath");
        String objectName = imgPath + UUIDUtil.get16UUID()+suffixName;
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        if(json.get("fileName") != null && StringUtils.isNotBlank(json.getString("fileName"))){
            objectName = imgPath + json.getString("fileName") + suffixName;
        }


        //String filePath = ;//"C:\\Users\\Administrator\\Desktop\\a02604f5cd493125abdf2cfcae98d2c1.mp4.f30.mp4";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(http+endpoint, accessKeyId, accessKeySecret);

        PutObjectResult objectResult ;
        try {
            InputStream inputStream = file.getInputStream();;//new FileInputStream(filePath);
            // 创建PutObject请求。
            objectResult = ossClient.putObject(bucketName, objectName, inputStream);
        } catch (Exception e) {
            System.out.println("Error Message:" + e.getMessage());
            throw new ServiceException("文件上传失败:"+e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String fileUrl = bindDomain+objectName;

        System.out.println(">>>>>>>>>>>>>>>>> 上传文件后的url:"+fileUrl);

        return fileUrl;
    }

    /**
     * 删除指定文件
     * @param json
     * @return
     */
    public static void fileDelete(JSONObject json) {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String http = "https://";
        String endpoint = json.getString("domain");//"oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = json.getString("accessKeyId");//"LTAnyDZ";
        String accessKeySecret = json.getString("accessKeySecret");//"VSG";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = json.getString("bucketName");//"ndl";
        //绑定的域名
        String bindDomain = json.getString("bindDomain");
        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
        String objectName = json.getString("imgUrl");

        //String yuming = http+bucketName+"."+ endpoint+"/";

        objectName = objectName.replace(bindDomain,"");

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

        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());
            throw new ServiceException("文件删除失败:"+oe.getErrorMessage());
        } 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());
            throw new ServiceException("文件删除失败:"+ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }


        System.out.println(">>>>>>>>>>>>>>>删除文件:" + objectName+" 成功!");
    }

    //创建桶
    public static String createBucket(Map<String,Object> map){

        String http = "https://";

        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = map.get("domain").toString();
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = map.get("accessKeyId").toString();
        String accessKeySecret = map.get("accessKeySecret").toString();
        // 填写Bucket名称,例如examplebucket。
        String bucketName = map.get("bucketName").toString();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(http+endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建CreateBucketRequest对象。
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);

            // 如果创建存储空间的同时需要指定存储类型和数据容灾类型, 请参考如下代码。
            // 此处以设置存储空间的存储类型为标准存储为例介绍。
            createBucketRequest.setStorageClass(StorageClass.Standard);
            // 数据容灾类型默认为本地冗余存储,即DataRedundancyType.LRS。如果需要设置数据容灾类型为同城冗余存储,请设置为DataRedundancyType.ZRS。
            //createBucketRequest.setDataRedundancyType(DataRedundancyType.ZRS);
            // 设置存储空间的权限为公共读,默认为私有。
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);

            // 创建存储空间。
            ossClient.createBucket(createBucketRequest);
        } 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();
            }
        }

        System.out.println(">>>>>>>>>>>>>>>新创建桶的名称:" + bucketName);
        return bucketName;
    }

    //本地上传文件
    public static String fileLocalUpload(Map<String,Object> map) {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String http = "https://";
        String endpoint = map.get("domain").toString();//"oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = map.get("accessKeyId").toString();//"55RnyDZ";
        String accessKeySecret = map.get("accessKeySecret").toString();//"Aui2oVSG";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = map.get("bucketName").toString();//"ddndl";

        //获取原文件名
        String filePath = map.get("filePath").toString();;
        //获取文件后缀
        String suffixName = filePath.substring(filePath.lastIndexOf("."));

        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        String objectName = "pdd_video/"+ UUID.randomUUID()+suffixName;

        //String filePath = ;//"C:\\Users\\Administrator\\Desktop\\a02604f5cd493125abdf2cfcae98d2c1.mp4.f30.mp4";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(http+endpoint, accessKeyId, accessKeySecret);

        PutObjectResult objectResult ;
        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObject请求。
            objectResult = ossClient.putObject(bucketName, objectName, inputStream);
        } catch (Exception e) {
            System.out.println("Error Message:" + e.getMessage());
            throw new ServiceException("文件上传失败:"+e.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String fileUrl = http+bucketName+"."+ endpoint+"/"+objectName;

        System.out.println(">>>>>>>>>>>>>>>>> 上传文件后的url:"+fileUrl);

        return fileUrl;
    }

    //根据OSS图片url得到缩略图url
    public static String getThumbnailUrl(String imgUrl){
        imgUrl = imgUrl + "?x-oss-process=image/resize,m_fill,w_400,quality,q_60";
        System.out.println(">>>>>>>>>>>>>>>>> 缩略图url:"+imgUrl);
        return imgUrl;
    }

    //根据OSS视频url得到视频封面图url
    public static String getVideoCoverlUrl(String videoUrl){
        videoUrl = videoUrl + "?x-oss-process=video/snapshot,t_7000,f_jpg,w_800,h_600,m_fast";
        System.out.println(">>>>>>>>>>>>>>>>> 视频封面图url:"+videoUrl);
        return videoUrl;
    }
}

maven  pom需引入的jar

<!--阿里云OSS-->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.10.2</version>
</dependency>
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐