springboot整合oss

上传图片到阿里云OSS

1. 引入依赖


        
            org.springframework.boot
            spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            com.aliyun.oss
            aliyun-sdk-oss
            2.2.0
        
        
            commons-fileupload
            commons-fileupload
            1.3.1
        
        
            org.projectlombok
            lombok
            1.16.18
        
        
            org.springframework.boot
            spring-boot-starter-web
        
        com.google.guava
            guava
            18.0
        
    
  • 其中包含SpringBoot相关依赖,文件上传,阿里云oss提供的第三方坐标,以及lombok。

2. 上传文件至oss所需参数dto

/**
 * @program: dome
 * @description: oss相关配置参数
 * @author: yxiumei
 * @create: 2019-06-8 15:40
 **/
@Data
@Component
@ConfigurationProperties(prefix = "oss")
public class OssSecretKey {

    /** 阿里云API的内或外网域名 */
    private String endPoint;

    private String appKey;

    private String appSecret;

    /** 分区名字*/
    private String bucketName;

    /** 文件夹名称 */
    private  String folder;

    /** oss 域名 */
    private String baseUrl;

}

3.在application.yml配置oss参数

oss:
  endPoint: "阿里云API的内或外网域名"
  appKey: ""
  appSecret: "秘钥"
  bucketName: "分区名称"
  folder: "文件夹名称"
  baseUrl: "oss域名"

4. 上传以及删除工具类开发

@Slf4j
@Component
@EnableConfigurationProperties
public class AliYunOssUtil {

    @Autowired
    private OssSecretKey ossSecretKey;

    /**
     * 上传文件至oss
     * @param file 文件信息
     * @return
     */
    public String uploadImg(File file) {
        OSSClient client = null;
        try {
            if (null != file) {
                // 获取oss配置信息
                String endpoint = ossSecretKey.getEndPoint();
                String accessKeyId = ossSecretKey.getAppKey();
                String accessKeySecret = ossSecretKey.getAppSecret();
                String bucketName = ossSecretKey.getBucketName();
                String folder = ossSecretKey.getFolder();
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
                String dateStr = format.format(new Date());

                // 初始化OSSClient
                client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                // 判断容器是否存在,不存在就创建
                if (!client.doesBucketExist(bucketName)) {
                    client.createBucket(bucketName);
                    CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                    createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                    client.createBucket(createBucketRequest);
                }
                // 设置文件路径和名称,上传文件
                String fileUrl = folder + "/" + (dateStr + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
                PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
                // 设置权限(公开读)
                client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                if (result != null) {
                    // 上传成功
                    return ossSecretKey.getBaseUrl() + "/" + fileUrl;
                } else {
                    log.error("Dream[]UserFiles[]uploadImg[]upload.img.fail");
                    return null;
                }
            } else {
                log.error("Dream[]AliYunOssUtil[]uploadImg[]upload.img.is.empty!");
                return null;
            }
        } catch (Exception e) {
            log.error("Dream[]AliYunOssUtil[]uploadImg[]upload.img.fail:{}", Throwables.getStackTraceAsString(e));
        } finally {
            if (null != client) {
                client.shutdown();
            }
        }
        return null;
    }

    /**
     * 删除图片
     * @param imgName
     * @return
     */
    public boolean deleteImg(String imgName) {
        OSSClient client = null;
        try {
            if (StringUtils.isEmpty(imgName)) {
                String endpoint = ossSecretKey.getEndPoint();
                String accessKeyId = ossSecretKey.getAppKey();
                String accessKeySecret = ossSecretKey.getAppSecret();
                String bucketName = ossSecretKey.getBucketName();
                client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                // 文件夹名 + 文件名
                imgName = "Dream/" + imgName;
                client.deleteObject(bucketName, imgName);
                client.shutdown();
                return true;
            } else {
                log.error("Dream[]AliYunOssUtil[]deleteImg[]file.name.is.null");
                return false;
            }
        } catch (Exception e) {
            log.error("Dream[]AliYunOssUtil[]deleteImg[]delete.file.fail:{}", Throwables.getStackTraceAsString(e));
            return false;
        } finally {
            if (null != client) {
                client.shutdown();
            }
        }
    }

    /**
     * 获取文件名后缀
     */
    public String fileSuffix(String fileName) {
        if (!StringUtils.isEmpty(fileName)) {
            String[] split = fileName.split("\\.");
            int suffixIndex = split.length - 1;
            return split[suffixIndex].toLowerCase();
        }
        return null;
    }

}

5.上传文件Controller

/**
 * @program: dome
 * @description: 上传图片
 * @author: yxiumei
 * @create: 2019-06-8 10:50
 **/
@Slf4j
@RestController
public class UploadImgController {

    private static final List ALLOWED_TYPES = Arrays.asList("jpeg", "png", "jpg", "gif", "pdf");

    @Autowired
    private AliYunOssUtil aliyunOSSUtil;
    @PostMapping(value = "upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        BufferedOutputStream out;
        String suffix = aliyunOSSUtil.fileSuffix(file.getOriginalFilename());
        if (!ALLOWED_TYPES.contains(suffix)) {
            log.info("OSSDome[]UploadImgController[]originalFilename[]file.suffix.error!");
            return null;
        }
            if (!file.isEmpty()) {
                String originalFilename = file.getOriginalFilename();
                if (StringUtils.isEmpty(originalFilename)) {
                    log.info("OSSDome[]UploadImgController[]originalFilename[]file.name.is.empty!");
                    return null;
                }
                // 实例化输出流
                File newFile = new File(originalFilename);
                out = new BufferedOutputStream(new FileOutputStream(newFile));
                out.write(file.getBytes());
                out.flush();

                return aliyunOSSUtil.uploadImg(newFile);
            }

        return null;
    }
}
  • 亲测可用

你可能感兴趣的:(随笔)