阿里云oss文件处理工具类

maven依赖

		<dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.15.0</version>
        </dependency>

工具类

package com.demo.util;

import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.util.Calendar;

import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author matao
 * @version OssUtil.java, v 0.1 2022年10月27日 16:51 matao
 */
//@Component
@Slf4j
public class OssUtil {

    @Value("${metadata.aliyun.endPoint}")
    private String endpoint;

    @Value("${metadata.aliyun.accessKey.default.id}")
    private String accessId;

    @Value("${metadata.aliyun.accessKey.default.secret}")
    private String accessSecret;

    @Value("${metadata.aliyun.oss.nameSpace}")
    private String ossNameSpace;

    private OSS client;

    /**
     * 上传文件到oss
     *
     * @param file     文件
     * @param filePath 文档存放路径
     * @return 文件访问地址
     */
    public String uploadFile(MultipartFile file, String filePath) {
        try {
            buildOssClient();

            InputStream inputStream = file.getInputStream();

            // 创建PutObjectRequest对象
            PutObjectRequest request = new PutObjectRequest(ossNameSpace, filePath, inputStream);
            // 文件上传时设置参数
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(inputStream.available());
            metadata.setCacheControl("no-cache");
            metadata.setHeader("Pragma", "no-cache");
            request.setMetadata(metadata);

            client.putObject(request);

            // 设置URL过期时间为10年
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.YEAR, 10);
            URL url = client.generatePresignedUrl(ossNameSpace, filePath, calendar.getTime());
            return url.toString();
        } catch (Exception e) {
            return null;
        } finally {
            closeOssClient();
        }
    }

    /**
     * 下载文件流
     *
     * @param filePath oss文件路径
     * @return 文件流
     */
    public InputStream downloadFile(String filePath) {
        InputStream inputStream;
        try {
            buildOssClient();

            // 判断文件是否存在
            if (!client.doesObjectExist(ossNameSpace, filePath)) {
                return null;
            }

            OSSObject object = client.getObject(ossNameSpace, filePath);
            if (ObjectUtil.isNull(object)) {
                return null;
            }

            inputStream = object.getObjectContent();
        } catch (Exception e) {
            return null;
        }
        return inputStream;
    }

    /**
     * 下载文件到本地
     *
     * @param remoteFilePath oss文件路径
     * @param localFilePath  要存放的文件本地路径
     * @param bucketName     文件目录
     */
    public void downloadFile(String remoteFilePath, String localFilePath, String bucketName) {
        try {
            buildOssClient();
            // 判断文件是否存在
            if (!client.doesObjectExist(bucketName, remoteFilePath)) {
                return;
            }

            // 读取文件到本地
            GetObjectRequest request = new GetObjectRequest(bucketName, remoteFilePath);
            client.getObject(request, new File(localFilePath));
        } catch (Exception ignored) {
        } finally {
            closeOssClient();
        }
    }

    /**
     * 创建bucket
     *
     * @param bucketName 文件目录
     */
    private void createBucket(String bucketName) {
        if (!client.doesBucketExist(bucketName)) {
            CreateBucketRequest bucketRequest = new CreateBucketRequest(bucketName);
            bucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            this.client.createBucket(bucketRequest);
        }
    }

    /**
     * 构建client
     */
    private void buildOssClient() {
        this.client = new OSSClientBuilder().build(endpoint, accessId, accessSecret);
    }

    /**
     * 关闭client
     */
    public void closeOssClient() {
        if (!ObjectUtil.isNull(client)) {
            this.client.shutdown();
        }
    }
}


你可能感兴趣的:(java,阿里云,java)