标签搜索

目 录CONTENT

文章目录

spring整合s3实现文件上传下载

高大北
2022-10-18 / 0 评论 / 0 点赞 / 90 阅读 / 1,908 字 / 正在检测是否收录...

pom依赖

       <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-s3 -->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.803</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-sts</artifactId>
            <version>1.11.803</version>
        </dependency>
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-core</artifactId>
            <version>1.11.803</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
            <scope>compile</scope>
        </dependency>

抽象接口

package com.ruoyi.common.utils.s3;

import java.io.File;
import java.util.Map;

public abstract class BaseObjectStorage {
 
    /**
     * 上传文件
     *
     * @param pathAndName
     * @param file
     */
    public abstract void upload(String pathAndName, File file);

    public abstract String upload( File file);
 
    /**
     * 授权
     *
     * @param pathAndName
     * @param time
     * @return
     */
    public abstract String authorize(String pathAndName, long time);
 
    /**
     * 授权(路径全)
     *
     * @param pathAndName
     * @param time
     * @return
     */
    public abstract String authorizeAllName(String pathAndName, long time);
 
    /**
     * 临时上传文件授权
     *
     * @param dir
     * @return
     */
    public abstract Map<String, Object> tokens(String dir);
 
    /**
     * 删除文件
     *
     * @param pathAndName
     */
    public abstract void deleteFile(String pathAndName);
 
}

具体上传

package com.ruoyi.common.utils.s3;
 
import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration;
import com.amazonaws.services.s3.AmazonS3;
 
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.securitytoken.AWSSecurityTokenService;
import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceAsyncClientBuilder;
import com.amazonaws.services.securitytoken.model.Credentials;
import com.amazonaws.services.securitytoken.model.GetFederationTokenRequest;
import com.amazonaws.services.securitytoken.model.GetFederationTokenResult;
import com.google.common.collect.Maps;
import com.ruoyi.common.utils.DateUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
 
import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.Map;
 
/**
 * s3cloud上传文件
 */
@Component
@Slf4j
public class S3ObjectStorage extends BaseObjectStorage {
 
 
    @Data
    @Component
    @ConfigurationProperties(prefix = "s3")
    public static class OssInfo {
        private String host;
        private String endpoint;
        private String accessKeyId;
        private String accessKeySecret;
        private String bucketName;
        private String rootDirectory;
        private String stsEndpoint;
        private String region;
    }
 
    @Autowired
    private OssInfo ossInfo;
 
    @Override
    public void upload(String pathAndName, File file) {
        AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
        AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
        try {
            String bucketPath = ossInfo.bucketName + "/" + ossInfo.rootDirectory;
            s3.putObject(new PutObjectRequest(bucketPath, DateUtils.getTimeFile() +pathAndName, file)
                    .withCannedAcl(CannedAccessControlList.PublicRead));
            log.info("===s3===上传文件记录:成功");
        } catch (AmazonServiceException ase) {
            log.error("===s3===文件上传服务端异常:", ase);
        } catch (AmazonClientException ace) {
            log.error("===s3===文件上传客户端异常:", ace);
        } finally {
            s3.shutdown();
        }
    }

    @Override
    public String upload( File file) {
        AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
        AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
        String url="";
        try {
            String bucketPath = ossInfo.bucketName + "/" + ossInfo.rootDirectory;
            String timeFile = DateUtils.getTimeFile();
            s3.putObject(new PutObjectRequest(bucketPath,  timeFile+file.getName(), file)
                    .withCannedAcl(CannedAccessControlList.PublicRead));
            log.info("===s3===上传文件记录:成功");
            url="https://web-index-resource.s3.us-east-2.amazonaws.com/"+bucketPath+"/"+timeFile+file.getName();
        } catch (AmazonServiceException ase) {
            log.error("===s3===文件上传服务端异常:", ase);
        } catch (AmazonClientException ace) {
            log.error("===s3===文件上传客户端异常:", ace);
        } finally {
            s3.shutdown();
        }
        return url;
    }
 
    @Override
    public String authorize(String pathAndName, long time) {
        AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
        AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
        try {
            Date expiration = new Date(System.currentTimeMillis() + time);
            URL url = s3.generatePresignedUrl(ossInfo.bucketName, ossInfo.rootDirectory + "/" + pathAndName, expiration);
            String resultUrl = url.toString();
            log.info("===s3===文件上传客户端返回url:{}", resultUrl);
            resultUrl = resultUrl.substring(0, resultUrl.indexOf("?"));
            resultUrl = resultUrl.replaceAll(ossInfo.host, ossInfo.endpoint);
            log.info("===s3===文件上传客户端返回url:{}", resultUrl);
            return resultUrl;
        } finally {
            s3.shutdown();
        }
    }
 
    @Override
    public String authorizeAllName(String pathAndName, long time) {
        AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
        AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
        try {
            Date expiration = new Date(System.currentTimeMillis() + time);
            URL url = s3.generatePresignedUrl(ossInfo.bucketName, pathAndName, expiration);
            String resultUrl = url.toString();
            resultUrl = resultUrl.replaceAll(ossInfo.host, ossInfo.endpoint);
            log.info("===s3==========authorizeAllName,S3文件上传客户端返回url:{}", resultUrl);
            return resultUrl;
        } finally {
            s3.shutdown();
        }
    }
 
    @Override
    public Map<String, Object> tokens(String dir) {
        Map<String, Object> result = null;
        AWSSecurityTokenService stsClient = null;
        try {
            result = Maps.newHashMap();
            AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
            EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.stsEndpoint, null);
            stsClient = AWSSecurityTokenServiceAsyncClientBuilder.standard().withCredentials(credential)
                    .withEndpointConfiguration(endpointConfiguration).build();
            GetFederationTokenRequest request = new GetFederationTokenRequest().withName("Bob")
                    .withPolicy("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Sid1\",\"Effect\":\"Allow\",\"Action\":[\"s3:*\"],\"Resource\":[\"*\"]}]}")
                    .withDurationSeconds(3600);
            GetFederationTokenResult response = stsClient.getFederationToken(request);
            Credentials tempCredentials = response.getCredentials();
 
 /*
            // TODO 备份获取Token
            stsClient = AWSSecurityTokenServiceClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret))).withRegion(ossInfo.region).build();
            //获取sessionToken实体
            GetSessionTokenRequest getSessionTokenRequest = new GetSessionTokenRequest().withDurationSeconds(3000);
            //创建请求
            Credentials tempCredentials = stsClient.getSessionToken(getSessionTokenRequest).getCredentials();
*/
 
            result.put("storeType", "s3");
            result.put("accessKeyId", tempCredentials.getAccessKeyId());
            result.put("sessionToken", tempCredentials.getSessionToken());
            result.put("secretKey", tempCredentials.getSecretAccessKey());
            result.put("expire", tempCredentials.getExpiration());
            result.put("dir", dir);
            result.put("bucketName", ossInfo.bucketName);
            result.put("region", ossInfo.region);
            result.put("host", "https://" + ossInfo.endpoint + "/" + ossInfo.bucketName);
            log.info("===s3===上传文件记录:accessKeyId:{},sessionToken:{}", tempCredentials.getAccessKeyId(), tempCredentials.getSessionToken());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != stsClient) {
                stsClient.shutdown();
            }
        }
        return result;
 
    }
 
    @Override
    public void deleteFile(String pathAndName) {
        AWSStaticCredentialsProvider credential = new AWSStaticCredentialsProvider(new BasicAWSCredentials(ossInfo.accessKeyId, ossInfo.accessKeySecret));
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration(ossInfo.endpoint, null);
        AmazonS3 s3 = AmazonS3ClientBuilder.standard().withCredentials(credential).withEndpointConfiguration(endpointConfiguration).build();
        try {
            s3.deleteObject(ossInfo.bucketName, ossInfo.bucketName + pathAndName);
        } finally {
            s3.shutdown();
        }
    }
 
 
}

用到的时间工具类

package com.ruoyi.common.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 * 
 * @author ruoyi
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static String YYYY_MM_DD_HH_MM_SS_File = "YYYY/MM/DD/HH/MM/SS";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", 
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     * 
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     * 
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }
    public static final String getTimeFile()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS_File);
    }
    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算相差天数
     */
    public static int differentDaysByMillisecond(Date date1, Date date2)
    {
        return Math.abs((int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)));
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }
}

配置文件

s3:
  endpoint: *******.s3.us-east-2.amazonaws.com
  access-key-id: ####
  access-key-secret: N/####/####
  bucket-name: 随便
  root-directory: 随便
  region: us-east-2
0

评论区