springboot整合amazonS3,封装上传文件接口

1.在pom.xml中引入amazonS3的依赖。

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

2.controller接口层

package com.example.demo.controller;

import com.example.demo.common.result.CodeMsg;
import com.example.demo.common.result.Result;
import com.example.demo.model.AmazonFileModel;
import com.example.demo.service.AmasonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;

/**
 * @Description: TODO
 * @author: 韩振亚
 * @date: 2021年06月09日 14:21
 */
@RestController
@RequestMapping("/amazonS3")
@Slf4j
public class AmazonController {
    /** 云存储中的测试数据目录,不允许删除 */
    final String DEMO = "/demo";

    @Autowired
    AmasonService amazonService;
    /**
     * @Description 文件上传云存储
     * @Param [file, params]
     * @return com.zhanglf.common.result.Result<com.zhanglf.model.AmazonFileModel>
     */
    @PostMapping(value = "/upload")
    public Result<AmazonFileModel> upload(@RequestParam("file") MultipartFile file, @RequestParam("params") String params, HttpServletRequest request){
        AmazonFileModel amazonFileModel= null;
        try{
            String uid = UUID.randomUUID().toString();
            amazonFileModel= amazonService.upload(file,uid);
        }catch (Exception e){
            log.error("上传云存储Exception",e.getCause());
            return Result.error(CodeMsg.SERVER_ERROR.fillArgs(e.getMessage()));
        }
        return Result.success(amazonFileModel);
    }
}

3.服务层和服务接口层

package com.example.demo.service;

import com.example.demo.model.AmazonFileModel;
import org.springframework.web.multipart.MultipartFile;

public interface AmasonService {
    /**
     * @Description 文件上传
     * @Param [file, uid]
     * @return com.zhanglf.model.AmazonFileModel
     */
    AmazonFileModel upload(MultipartFile file, String uid);
}


package com.example.demo.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.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.example.demo.model.AmazonFileModel;
import com.example.demo.service.AmasonService;
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;

/**
 * @Description: TODO
 * @author: 韩振亚
 * @date: 2021年06月09日 11:36
 */
@Service
public class AmazonServiceImpl implements AmasonService {
    /** bucket */
    final String bucketName = "hzy-bucket";
    /** accessKey */
    final String accessKey = "minioadmin";
    /** secretKey */
    final String secretKey = "minioadmin";
    /** endpoint */
    final String endpoint = "http://127.0.0.1:9000";
    /** aws s3 client */
    AmazonS3 s3 = null;
    @Override
    public AmazonFileModel upload(MultipartFile file, String uid) {
        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 = bucketName+dateDir;
        String filePath = dateDir+"/"+tempFileName;
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(contentType);
        objectMetadata.setContentLength(fileSize);
        try {
            PutObjectResult putObjectResult = s3.putObject(tempBucketName, tempFileName, file.getInputStream(), objectMetadata);
        } catch (AmazonServiceException e) {
            System.out.println(e.getErrorMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        AmazonFileModel amazonFileModel = new AmazonFileModel ();
        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, "cn-north-1");

        AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey,secretKey);
        AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);

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

4.相关的实体类

package com.example.demo.model;

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

/**
 * @Description: TODO
 * @author: 韩振亚
 * @date: 2021年06月09日 10:19
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class AmazonFileModel {
    /** 文件大小 */
    private long fileSize;
    /** 文件名称 */
    private String fileName;
    /** 文件URL */
    private String url;
    /** 云存储中的路径 */
    private String filePath;
    /** 文件类型 */
    private String fileType;
}

package com.example.demo.common.result;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * @Description: TODO
 * @author: 韩振亚
 * @date: 2021年06月09日 10:22
 */
@AllArgsConstructor
@Getter
public class Result<T> {
    /**
     * 返回代码
     */
    private int code;
    /**
     * 返回消息
     */
    private String msg;
    /**
     * 返回数据
     */
    private T data;

    /**
     * 成功时候的调用
     * */
    public static <T> Result<T> success(T data){
        return new  Result<T>(0,"success",data);
    }
    /**
     * 成功时候的调用
     * */
    public static Result success(){
        return new  Result(0,"success",null);
    }

    /**
     * 失败时候的调用
     * */
    public static <T> Result<T> error(CodeMsg codeMsg){
        if(codeMsg == null) {
            return null;
        }
        return new Result<T>(codeMsg.getCode(),codeMsg.getMsg(),null);
    }
}

package com.example.demo.common.result;

import lombok.Getter;

/**
 * @Description: TODO
 * @author: 韩振亚
 * @date: 2021年06月09日 11:30
 */
@Getter
public class CodeMsg {
    //通用信息
    /** 成功 */
    public static CodeMsg SUCCESS = new CodeMsg(0, "success");
    /** 服务器异常 */
    public static CodeMsg SERVER_ERROR = new CodeMsg(500000,"服务端异常:%s");
    /** 参数校验异常 */
    public static CodeMsg BIND_ERROR = new CodeMsg(500001,"参数校验异常:%s");
    /** 传入参数为空 */
    public static CodeMsg PARAMS_IS_EMPTY = new CodeMsg(500002,"传入参数为空:%s");
    /** 参数解析失败 */
    public static CodeMsg PARAMS_PARSE_ERROR = new CodeMsg(500003,"参数解析失败:%s");


    //登录模块 5001XX
    /** 账号不存在 */
    public static CodeMsg ACCOUNT_NOT_EXIST = new CodeMsg(500100,"账号不存在:%s");
    /** 账号已存在 */
    public static CodeMsg ACCOUNT_EXISTS = new CodeMsg(500101,"账号已存在:%s");
    /** 密码不正确 */
    public static CodeMsg PASSWORD_ERROR = new CodeMsg(500102,"密码不正确:%s");

    //权限模块 5002XX

    //云中间件模块 5003XX
    /** 云存储异常 */
    public static CodeMsg OSS_ERROR = new CodeMsg(500300,"云存储异常:%s");


    /**
     * 参数为空
     */
    public static CodeMsg PARAM_EMPTY = new CodeMsg(400001,"参数:%s不能为空!");
    /**
     * 表中已经存在该字段
     */
    public static CodeMsg FIELD_EXIST = new CodeMsg(400002,"%s");

    /**
     * 状态为已发布
     */
    public static CodeMsg PUBLIC_STATUS = new CodeMsg(400003,"状态为已发布,不允许修改或删除操作!");

    //执行数据库操作异常模块  5004XX

    /**执行新增时数据库异常*/
    public static CodeMsg MYSQL_INSERT_EXCEPTION = new CodeMsg(500401,"执行新增时数据库异常:%s");

    /**执行修改时数据库异常*/
    public static CodeMsg MYSQL_UPDATE_EXCEPTION = new CodeMsg(500402,"执行修改时数据库异常:%s");

    /**执行删除时数据库异常*/
    public static CodeMsg MYSQL_DELETE_EXCEPTION = new CodeMsg(500403,"执行删除时数据库异常:%s");

    /**执行查询时数据库异常*/
    public static CodeMsg MYSQL_QUERY_EXCEPTION = new CodeMsg(500404,"执行查询时数据库异常:%s");

    /**执行批量插入时插入条数小于入参条数*/
    public static CodeMsg MYSQL_BATCH_INSERT_EXCEPTION = new CodeMsg(500405,"批量插入数量不对:%s");


    /**数据状态不允许进行某些操作*/
    public static CodeMsg STATUS_ERROR = new CodeMsg(500406,"%s");



    /** 返回码 */
    private int code;
    /** 返回信息 */
    private String msg;
    /** 无参构造方法 */
    private CodeMsg() {
    }
    /** 构造方法 */
    private CodeMsg(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
    /** 填充动态参数 */
    public CodeMsg fillArgs(Object... args) {
        int code = this.code;
        String message = String.format(this.msg, args);
        return new CodeMsg(code, message);
    }
}

5.修改配置文件上传文件限制

#设置单个文件的大小
spring.servlet.multipart.max-request-size=50MB
#设置单次请求的文件的总大小
spring.servlet.multipart.max-file-size=200MB

6.接口请求测试:postman

 

 接口请求返回值:

{
    "code": 0,
    "msg": "success",
    "data": {
        "fileSize": 3226253,
        "fileName": "3.9智慧应急投标技术方案(华骏)(1)(1).docx",
        "url": "http://127.0.0.1:9000//2021/06/09/3.9智慧应急投标技术方案(华骏)(1)(1).docx",
        "filePath": "/2021/06/09/3.9智慧应急投标技术方案(华骏)(1)(1).docx",
        "fileType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    }
}

  

posted @ 2021-06-09 15:06  hzy_叶子  阅读(1606)  评论(0编辑  收藏  举报