当前位置:   article > 正文

Springboot整合AWS s3 存储_springboot aws s3

springboot aws s3

依赖

  <!--aws s3-->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
        </dependency>


        <aws.s3.version>1.11.543</aws.s3.version>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Aws yaml 配置

amazon:
  aws:
    access-key-id: AKIAT
    access-key-secret: Tv7Ck
  s3:
    default-bucket: 
    region: 
    endpoint: https://.com/
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Config


import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * ClassName AwsConfig
 *
 * @author wang
 * Date 2022/6/23 10:19
 */
@Configuration
@Component
public class AwsConfig {

    @Value("${amazon.aws.access-key-id}")
    private String accessKey;
    @Value("${amazon.aws.access-key-secret}")
    private String secretKey;
    @Value("${amazon.s3.region}")
    private String region;

    @Bean
    public AmazonS3 s3Client() {
        AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);
        return AmazonS3ClientBuilder.standard()
                .withRegion(Regions.fromName(region))
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .build();

    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

service


import cn.hutool.core.util.IdUtil;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;

/**
 * ClassName AwsSysFileServiceImpl
 *
 * @author wang
 * Date 2022/6/23 10:11
 */
@Service
@RequiredArgsConstructor
public class AwsSysFileService {

    final AmazonS3 s3Client;

    @Value("${amazon.aws.access-key-id}")
    private String accessKey;
    @Value("${amazon.s3.default-bucket}")
    private String bucketName;
    @Value("${amazon.s3.endpoint}")
    private String endpoint;
    @Value("${spring.profiles.active}")
    private String env;


    public String uploadFile(MultipartFile multipartFile, String source) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();
        assert originalFilename != null;
        FileTypeUtils.checkFileType(originalFilename);
        String fileName = this.generateFileName(originalFilename);
        File file = this.convertMultiPartToFile(multipartFile);
        String filePath = bucketName + "/" + "test" + "/"+ source + "/" + SDFFactory.DATE_DASH.format(new Date());
        this.uploadFileToS3bucket(filePath, fileName, file);
        file.delete();
        return endpoint + filePath + "/" + fileName;
    }

    /**
     * 创建临时文件
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    private File convertMultiPartToFile(MultipartFile multipartFile) throws IOException {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件后缀
        assert fileName != null;
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名,防止生成的临时文件重复
        File excelFile = File.createTempFile(IdUtil.randomUUID(), prefix);
        // MultipartFile to File
        multipartFile.transferTo(excelFile);
        return excelFile;
    }

    private String generateFileName(String originalFilename) {
        return System.currentTimeMillis() + "-" + originalFilename.replace(" ", "_");
    }

    private void uploadFileToS3bucket(String filePath, String fileName, File file) {
        s3Client.putObject(new PutObjectRequest(filePath, fileName, file)
                .withCannedAcl(CannedAccessControlList.PublicRead));
    }

    public void deleteFileFromS3Bucket(String fileUrl) {
        String fileName = fileUrl.replaceAll(endpoint, "");
        s3Client.deleteObject(new DeleteObjectRequest(bucketName, fileName));
    }

    public void downloadFile(String fileUrl) throws IOException {
        ResponseHeaderOverrides headerOverrides = new ResponseHeaderOverrides()
                .withCacheControl("No-cache")
                .withContentDisposition("attachment; filename=example.txt");
        GetObjectRequest getObjectRequestHeaderOverride = new GetObjectRequest(fileUrl, accessKey)
                .withResponseHeaders(headerOverrides);
        S3Object headerOverrideObject = s3Client.getObject(getObjectRequestHeaderOverride);
        displayTextInputStream(headerOverrideObject.getObjectContent());
    }


    private void displayTextInputStream(InputStream input) throws IOException {
        // Read the text input stream one line at a time and display each line.
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        System.out.println();
    }


}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/707012
推荐阅读
相关标签
  

闽ICP备14008679号