springboot阿里云oss工具类

Posted Sappy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot阿里云oss工具类相关的知识,希望对你有一定的参考价值。

pom依赖;

yml配置:

读取配置文件类:

上传:

完整工具类代码:

点击查看代码
`
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.luzhizheng.common.config.OSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Sappy
 * @date 4/6/2023 10:40:44
 */

@Component
public class AliYunOSSUtil 
    @Autowired
    private OSSConfig ossConfig;

    private static String FOLDER = "文件夹";

    /**
     * 本地文件上传到oss
     * @param file
     * @return
     * @throws FileNotFoundException
     */
    public String upload(File file) throws FileNotFoundException 
        String absolutePath = file.getAbsolutePath();
        String fileName = file.getName();
        FileInputStream is = new FileInputStream(absolutePath);
        ObjectMetadata metadata = new ObjectMetadata();
        int indexOfLastDot = fileName.lastIndexOf(".");
        String suffix = fileName.substring(indexOfLastDot);
        metadata.setContentType(getContentType(suffix));
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        fileName = uuid + suffix;
        String datePath = DateTimeFormatter.ISO_DATE.format(LocalDate.now());
        fileName = FOLDER + "/" + datePath + "/" + fileName;
        PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucket(), fileName, is);
        //设置ContentType,预览
        putObjectRequest.setMetadata(metadata);
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        ossClient.putObject(putObjectRequest);
/*        //临时第三方授权
        Date expiration = new Date(System.currentTimeMillis() + 3600000L  * 24);
        URL url = ossClient.generatePresignedUrl(ossConfig.getBucket(), aimFilePathName, expiration);*/
        String url = "https://" + ossConfig.getBucket() + "." + ossConfig.getEndpoint() + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;
    


    /**
     * multipartFile上传到oss
     * @param multipartFile
     * @return
     * @throws IOException
     */
    public String upload(MultipartFile multipartFile) throws IOException 
        InputStream inputStream = multipartFile.getInputStream();
        String fileName = multipartFile.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        fileName = uuid + fileName;
        String datePath = DateTimeFormatter.ISO_DATE.format(LocalDate.now());
        // 拼接fileName , 文件夹1/文件夹2/文件名.jpg
        fileName = FOLDER + "/" + datePath + "/" + fileName;
        // 如果需要上传时设置存储类型与访问权限
        ObjectMetadata metadata = new ObjectMetadata();
        int indexOfLastDot = fileName.lastIndexOf(".");
        String suffix = fileName.substring(indexOfLastDot);
        metadata.setContentType(getContentType(suffix));
        PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucket(), fileName, inputStream);
        //设置ContentType,预览
        putObjectRequest.setMetadata(metadata);
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        ossClient.putObject(putObjectRequest);
        /*        //临时第三方授权
        Date expiration = new Date(System.currentTimeMillis() + 3600000L  * 24);
        URL url = ossClient.generatePresignedUrl(ossConfig.getBucket(), aimFilePathName, expiration);*/
        String url = "https://" + ossConfig.getBucket() + "." + ossConfig.getEndpoint() + "/" + fileName;
        ossClient.shutdown();
        return url;
    

    private static String getContentType(String suffix) 
        if (suffix.equalsIgnoreCase(".bmp")) 
            return "image/bmp";
        
        if (suffix.equalsIgnoreCase(".gif")) 
            return "image/gif";
        
        if (suffix.equalsIgnoreCase(".jpeg") ||
            suffix.equalsIgnoreCase(".jpg") ||
            suffix.equalsIgnoreCase(".png")
        ) 
            return "image/jpg";
        
        return "image/jpg";
    


    /**
     * 列举 指定路径下所有的文件的文件名
     * 如果要列出根路径下的所有文件,path= ""
     *
     * @param path
     * @return
     */
    public List<String> listFileName(String path) 
        // 构造ListObjectsRequest请求。
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossConfig.getBucket());
        // 设置prefix参数来获取path目录下的所有文件。
        listObjectsRequest.setPrefix(path);
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        // 列出文件。
        ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
        List<OSSObjectSummary> objectSummaries = objectListing.getObjectSummaries();
        List<String> list = objectSummaries.stream().map(OSSObjectSummary::getKey).collect(Collectors.toList());
        ossClient.shutdown();
        return list;
    

    /**
     * 列举文件下所有的文件url信息
     */
    public List<String> listFileUrl(String path) 
        List<String> res = new ArrayList<>();

        // 构造ListObjectsRequest请求
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(ossConfig.getBucket());

        // 设置prefix参数来获取fun目录下的所有文件。
        listObjectsRequest.setPrefix(path);

        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

        // 列出文件。
        ObjectListing listing = ossClient.listObjects(listObjectsRequest);
        // 遍历所有文件。

        for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) 
            //文件访问路径
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
            URL url = ossClient.generatePresignedUrl(ossConfig.getBucket(), objectSummary.getKey(), expiration);
            res.add(url.toString());
        
        // 关闭OSSClient。
        ossClient.shutdown();
        return res;
    

    /**
     * 判断文件是否存在
     *
     * @param objectName
     * @return
     */
    public boolean isFileExist(String objectName) 
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        return ossClient.doesObjectExist(ossConfig.getBucket(), objectName);
    

    /**
     * 通过文件名下载文件
     *
     * @param ossFileName    要下载的文件名
     * @param localFileName 本地要创建的文件名
     */
    public void downloadFile(String ossFileName, String localFileName) 
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());

        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖,不存在则新建。
        ossClient.getObject(new GetObjectRequest(ossConfig.getBucket(), ossFileName), new File(localFileName));
        // 关闭OSSClient。
        ossClient.shutdown();
    

    /**
     * 删除文件或目录
     *
     * @param objectName
     */
    public void deleteFile(String objectName) 
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        ossClient.deleteObject(ossConfig.getBucket(), objectName);
        ossClient.shutdown();
    

    /**
     * 批量删除文件或目录
     *
     * @param keys
     */
    public void deleteFiles(List<String> keys) 
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        // 删除文件。
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(ossConfig.getBucket()).withKeys(keys));
        deleteObjectsResult.getDeletedObjects();
        ossClient.shutdown();
    

    /**
     * 创建文件夹
     *
     * @param folder
     * @return
     */
    public String createFolder(String folder) 
        // 文件夹名
        final String keySuffixWithSlash = folder;
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        // 判断文件夹是否存在,不存在则创建
        if (!ossClient.doesObjectExist(ossConfig.getBucket(), keySuffixWithSlash)) 
            // 创建文件夹
            ossClient.putObject(ossConfig.getBucket(), keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
            // 得到文件夹名
            OSSObject object = ossClient.getObject(ossConfig.getBucket(), keySuffixWithSlash);
            String fileDir = object.getKey();
            ossClient.shutdown();
            return fileDir;
        
        return keySuffixWithSlash;
    



`````

SpringBoot整合阿里云OSS

SpringBoot整合阿里云OSS

为了解决海量数据存储与弹性扩容,项目中我们采用云存储的解决方案- 阿里云OSS

1.准备工作

1.1 开通“对象存储OSS”服务

步骤:

  1. 申请阿里云账号
  2. 实名认证
  3. 开通“对象存储OSS”服务
  4. 进入管理控制台

详细可以参考:OSS的购买和配置

1.2 创建Bucket

进入到管理控制台的Bucket列表创建一个Bucket

如下:

1.3 创建RAM子用户

创建操作阿里云OSS许可证(阿里云颁发id和秘钥):

创建AccessKey

2.SpringBoot整合阿里云OSS

官方文档参考:对象存储OSS Java SDK

2.1 创建SpringBoot项目

导入依赖:

<dependencies>
    <!--aliyunOSS-->
    <dependency>
        <groupId>com.aliyun.oss</groupId>
        <artifactId>aliyun-sdk-oss</artifactId>
        <version>2.8.3</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
</dependencies

2.2 配置application.properties

进入到对应的Bucket列表查看地域节点:

#服务端口
server.port=8002
#服务名
spring.application.name=service-oss
#环境设置:dev、test、prod
spring.profiles.active=dev

#阿里云 OSS
#不同的服务器,地址不同
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=LTAI5tGxxxxK4aAa
aliyun.oss.file.keysecret=zE4nEzmcUxxWRk0tytJKD
#bucket可以在控制台创建,也可以使用java代码创建
aliyun.oss.file.bucketname=xppll

2.3 创建常量读取工具类

创建常量读取工具类ConstantPropertiesUtils

/**
 * @author xppll
 * @date 2021/12/2 19:11
 */
@Component
public class ConstantPropertiesUtils implements InitializingBean 
    //读取配置文件的内容
    @Value("$aliyun.oss.file.endpoint")
    private String endpoint;
    @Value("$aliyun.oss.file.keyid")
    private String keyId;
    @Value("$aliyun.oss.file.keysecret")
    private String keySecret;
    @Value("$aliyun.oss.file.bucketname")
    private String bucketName;

    //定义公共静态常量
    public static String END_POINT;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;

    @Override
    public void afterPropertiesSet() throws Exception 
        END_POINT = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
    

2.4 上传图片至阿里云

controller层:

/**
 * @author xppll
 * @date 2021/12/2 19:36
 */
@CrossOrigin
@RestController
@RequestMapping("eduoss/fileoss")
public class OssController 

    @Autowired
    private OssService ossService;
    //上传头像,返回图片的url给
    @PostMapping
    public R uploadOssFile(MultipartFile file)
        //获取上传文件 MultipartFile
        //返回图片在oss上的路径
        String url = ossService.uploadFileAvatar(file);
        return R.ok().data("url",url);
    

service层:

/**
 * @author xppll
 * @date 2021/12/2 19:36
 */
@Service
public class OssServiceImpl implements OssService 
    @Override
    public String uploadFileAvatar(MultipartFile file) 

        String endpoint = ConstantPropertiesUtils.END_POINT;
        String accessKeyId = ConstantPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtils.BUCKET_NAME;
        String url = null;

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

            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();

            //保证文件名唯一,去掉uuid中的'-'
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;

            //把文件按日期分类,构建日期路径:avatar/2019/02/26/文件名
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //拼接
            fileName=datePath+"/"+fileName;

            //调用oss方法上传到阿里云
            //第一个参数:Bucket名称
            //第二个参数:上传到oss文件路径和文件名称
            //第三个参数:上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);

            //把上传后把文件url返回
            //https://xppll.oss-cn-beijing.aliyuncs.com/01.jpg
            url = "https://" + bucketName + "." + endpoint + "/" + fileName;
            //关闭OSSClient
            ossClient.shutdown();
         catch (IOException e) 
            e.printStackTrace();
        

        return url;
    

2.5 使用swagger测试

上传成功,并实现了日期分类:


最后喜欢的小伙伴,记得三连哦!😏🍭😘

以上是关于springboot阿里云oss工具类的主要内容,如果未能解决你的问题,请参考以下文章

阿里云OSS工具类

阿里云OSS上传文件 工具类拿来直接用

springboot 集成阿里云oss

交友项目自动装配模块封装阿里云发送短信&Oss对象存储&百度云人脸识别

SpringBoot上传文件到阿里云OSS

Springboot上传文件到阿里云对象存储OSS的几种常用方法