SpringBoot 上传文件到AWS S3 代码实现

文章目录

  • 前言
    • 1. 引入依赖
    • 2. 配置application文件
    • 3. 新建实体类
    • 4. 新建服务实现类
    • 5. 新建服务类
    • 6. 新建控制层类
    • 7.postman演示
  • 总结


前言

这篇文章主要介绍了SpringBoot实现上传文件到AWS S3的代码,希望帮助大家解决问题,感兴趣的朋友可以了解下

下面直接上代码

1. 引入依赖

   <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.347</version>
            <scope>compile</scope>
    </dependency>

2. 配置application文件

  s3:
    region: us-east-1
    accessKeyId: xxx
    accessKeySecret: xxx
    bucketName: xxx(存储桶的名字)
    endpoint: 服务器地址

3. 新建实体类

package vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @Description 云存储文件模型
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AmazonFileVO {
    /**
     * 文件大小
     */
    private long fileSize;

    /**
     * 文件名称
     */
    private String fileName;

    /**
     * 文件URL
     */
    private String url;

    /**
     * 云存储中的路径
     */
    private String filePath;

    /**
     *  文件类型
     */
    private String fileType;
}

4. 新建服务实现类

package service.impl;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.sino.platform.service.cgm.vo.AmazonFileVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 服务实现类
 * @since 2020-06-22
 */
@Service
public class uploadServiceImpl implements uploadService {

    AmazonS3 s3 = null;

    @Value("${s3.accessKeyId}")
    private String accessKeyId;

    @Value("${s3.accessKeySecret}")
    private String accessKeySecret;

    @Value("${s3.bucketName}")
    private String bucketName;

    @Value("${s3.region}")
    private String regionName;

    @Value("${s3.endpoint}")
    private String endpoint;

    private String FolderName = "xx/";

    public AmazonFileVO upload(MultipartFile file) {
        String tempFileName = file.getOriginalFilename();
        String originalFileName = file.getOriginalFilename();
        String contentType = file.getContentType();
        long fileSize = file.getSize();
        String dateDir = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String tempBucketName = FolderName + dateDir;
        String filePath = tempBucketName +"/"+ tempFileName;
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(contentType);
        objectMetadata.setContentLength(fileSize);
        try {

            PutObjectResult putObjectResult = s3.putObject(tempBucketName, tempFileName, file.getInputStream(), objectMetadata);
            //文件权限,设置为公共读
            s3.setObjectAcl(tempBucketName, tempFileName, CannedAccessControlList.PublicRead);
        } catch (AmazonServiceException e) {
            System.out.println(e.getErrorMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        AmazonFileVO amazonFileModel = new AmazonFileVO();
        amazonFileModel.setFileName(originalFileName);
        amazonFileModel.setFileSize(fileSize);
        amazonFileModel.setFileType(contentType);
        amazonFileModel.setFilePath(filePath);
        amazonFileModel.setUrl(endpoint + "/" + filePath);
        return amazonFileModel;
    }


    @PostConstruct
    public void init() {

        ClientConfiguration config = new ClientConfiguration();
        AwsClientBuilder.EndpointConfiguration endpointConfig =
                new AwsClientBuilder.EndpointConfiguration(endpoint, regionName);
        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKeyId, accessKeySecret);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);

        s3 = AmazonS3Client.builder()
                .withEndpointConfiguration(endpointConfig)
                .withClientConfiguration(config)
                .withCredentials(awsCredentialsProvider)
                .disableChunkedEncoding()
                .withPathStyleAccessEnabled(true)
                .build();
    }

}

5. 新建服务类

package service;

import com.sino.platform.service.cgm.vo.AmazonFileVO;
import org.springframework.web.multipart.MultipartFile;


/**
 * 服务类
 */
public interface uploadService {


    /**
     * @Description 文件上传
     * @Param [file, uid]
     * @return com.zhanglf.model.AmazonFileModel
     */
    AmazonFileVO upload(MultipartFile file);


}

6. 新建控制层类

   @ApiOperation(value = "上传apk到s3", notes = OperationType.INSERT, response = R.class)
   @PostMapping(value = "/upload")
    public R upload(@RequestParam("file") MultipartFile file){
        AmazonFileVO amazonFileModel= null;
        try{
            amazonFileModel= appVersionService.upload(file);
        }catch (Exception e){
            return R.fail(e.getMessage());
        }
        return R.data(amazonFileModel);
    }

7.postman演示

SpringBoot 上传文件到AWS S3 代码实现_第1张图片

总结

以上就是今天要讲的内容,本文仅仅简单介绍了上传文件到AWS S3 代码实现,随笔记录。

你可能感兴趣的:(springboot学习,spring,boot)