阿里云的OSS工具类

做~自己de王妃 提交于 2019-12-13 10:41:11

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

一、pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-parent</artifactId>
      <version>2.2.2.RELEASE</version>
      <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.atzhongruan</groupId>
   <artifactId>springboot_oss</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>springboot_oss</name>
   <description>Demo project for Spring Boot</description>

   <properties>
      <java.version>1.8</java.version>
   </properties>

   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-web</artifactId>
      </dependency>

      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-test</artifactId>
         <scope>test</scope>
         <exclusions>
            <exclusion>
               <groupId>org.junit.vintage</groupId>
               <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
         </exclusions>
      </dependency>
      <!-- httpclient -->
      <dependency>
         <groupId>org.apache.httpcomponents</groupId>
         <artifactId>httpclient</artifactId>
         <version>4.4</version>
      </dependency>

      <dependency>
         <groupId>org.apache.httpcomponents</groupId>
         <artifactId>httpcore</artifactId>
         <version>4.4</version>
      </dependency>

      <!-- 阿里对象存储 -->
      <dependency>
         <groupId>com.aliyun.oss</groupId>
         <artifactId>aliyun-sdk-oss</artifactId>
         <version>2.8.3</version>
      </dependency>
      <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
      <dependency>
         <groupId>org.apache.commons</groupId>
         <artifactId>commons-lang3</artifactId>
         <version>3.8.1</version>
      </dependency>
      <dependency>
         <groupId>commons-io</groupId>
         <artifactId>commons-io</artifactId>
         <version>2.4</version>
      </dependency>
   </dependencies>

   <build>
      <plugins>
         <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
         </plugin>
      </plugins>
   </build>

</project>

二、OSSUtil

package com.atzhongruan.springboot_oss.utils;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.time.DateUtils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.fasterxml.jackson.annotation.JsonValue;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <一句话功能简述>
 * <功能详细描述>
 *
 * @author Administrator
 * @version [版本号, 2019/12/13 0013]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class OssUtil {
    /**
     * 域名
     */
    private final static String OSS_END_POINT = "http://oss-cn-beijing.aliyuncs.com";

    /**
     * 账号
     */
    private final static String OSS_ACCESS_KEY_ID = "AI4FoJBmgdjQrYA5tePDDi";

    /**
     * 密匙
     */
    private final static String OSS_ACCESS_KEY_SECRET = "oDCrl6NedxMgFazOscSB1lWemGsy";

    /**
     * 存储空间
     */
    private final static String OSS_BUCKET_NAME = "zzx-oss";

    /**
     * URL有效期
     */
    private final static Date OSS_URL_EXPIRATION = DateUtils.addDays(new Date(), 365 * 10);

    private volatile static OSSClient instance = null;

    private OssUtil() {
    }

    /**
     * Oss 实例化
     *
     * @return
     */
    private static OSSClient getOssClient() {
        if (instance == null) {
            synchronized (OssUtil.class) {
                if (instance == null) {
                    instance = new OSSClient(OSS_END_POINT, OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET);
                }
            }
        }
        return instance;
    }

    /**
     * 文件路径的枚举
     */
    public enum FileDirType {

        ARTICLE_IMAGES("article_images"), ARTICLE_VIDEO("article_video"), CAROUSEL("carousel"), MENU("menu");

        private String dir;

        FileDirType(String dir) {
            this.dir = dir;
        }

        @JsonValue
        public String getDir() {
            return dir;
        }
    }

    /**
     * 当Bucket 不存在时候创建Bucket
     */
    private static void createBuchet() {
        try {
            if (!OssUtil.getOssClient().doesBucketExist(OSS_BUCKET_NAME)) {
                OssUtil.getOssClient().createBucket(OSS_BUCKET_NAME);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ClientException("创建Bucket失败,请核对Bucket名称(规则:只能包含小写字母、数字和短横线,必须以小写字母和数字开头和结尾,长度在3-63之间)");
        }
    }

    /**
     * 文件上传的文件后缀
     *
     * @param FilenameExtension
     * @return
     */
    private static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
                FilenameExtension.equalsIgnoreCase("jpg") ||
                FilenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        return "multipart/form-data";
    }

    /**
     * 上传OSS服务器 如果同名文件会覆盖服务器上的
     *
     * @param file
     * @param fileDirType
     * @return
     */
    private static String uploadFile(MultipartFile file, FileDirType fileDirType) {
        String fileName = String.format("%s.%s", UUID.randomUUID().toString(), FilenameUtils.getExtension(file.getOriginalFilename()));
        try (InputStream inputStream = file.getInputStream()) {

            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(FilenameUtils.getExtension("." + file.getOriginalFilename()));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            PutObjectResult putObjectResult = OssUtil.getOssClient().putObject(OSS_BUCKET_NAME, fileDirType.getDir() + "/" + fileName, inputStream, objectMetadata);
            System.out.println(putObjectResult);
            return fileDirType.getDir() + "/" + fileName;
        } catch (OSSException oe) {
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:    " + oe.getErrorCode());
            System.out.println("Request ID:    " + oe.getRequestId());
            System.out.println("Host ID:       " + oe.getHostId());
            return null;
        } catch (ClientException ce) {
            System.out.println("Error Message: " + ce.getMessage());
            return null;
        } catch (IOException e) {
            System.out.println("Error Message: " + e.getMessage());
            return null;
        }
    }

    /**
     * 获取文件路径
     *
     * @param fileUrl
     * @param fileDirType
     * @return
     */
    private static String getFileUrl(String fileUrl, FileDirType fileDirType) {
        if (StringUtils.isEmpty(fileUrl)) {
            throw new RuntimeException("文件地址为空!");
        }
        String[] split = fileUrl.split("/");

        URL url = OssUtil.getOssClient().generatePresignedUrl(OSS_BUCKET_NAME, fileDirType.getDir() + "/" + split[split.length - 1], OSS_URL_EXPIRATION);
        if (url == null) {
            throw new RuntimeException("获取OSS文件URL失败!");
        }
        return url.toString();
    }

    /**
     * 文件上传 去掉URL中的?后的时间戳
     *
     * @param file
     * @param fileDirType
     * @return
     */
    public static String upload(MultipartFile file, FileDirType fileDirType) {
        OssUtil.createBuchet();
        String fileName = OssUtil.uploadFile(file, fileDirType);
        String fileOssUrl = OssUtil.getFileUrl(fileName, fileDirType);
        int firstChar = fileOssUrl.indexOf("?");
        if (firstChar > 0) {
            fileOssUrl = fileOssUrl.substring(0, firstChar);
        }
        return fileOssUrl;
    }

    /**
     * 获取路径地址
     *
     * @param fileName
     * @return
     */
    public static String getPathUrl(String fileName) {
        return fileName.substring(fileName.indexOf(OSS_END_POINT) + OSS_END_POINT.length() + 1);
    }

    /**
     * 文件删除
     *
     * @param keys
     */
    public static void delete(List<String> keys) {
        List<String> newKeys = keys.stream().map((item) -> {
            return OssUtil.getPathUrl(item);
        }).collect(Collectors.toList());
        try {
            DeleteObjectsResult deleteObjectsResult = OssUtil.getOssClient().deleteObjects(new DeleteObjectsRequest(OSS_BUCKET_NAME).withKeys(newKeys));
            List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            System.out.println(deletedObjects);
        } catch (OSSException oe) {
            System.out.println("Error Message: " + oe.getErrorCode());
            System.out.println("Error Code:    " + oe.getErrorCode());
            System.out.println("Request ID:    " + oe.getRequestId());
            System.out.println("Host ID:       " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Error Message: " + ce.getMessage());
        }

    }

}

三、实体类 JsonResult

public class JsonResult {
    private String code;
    private String message;
   //get和set和构造函数
}

四、测试类TestController

package com.atzhongruan.springboot_oss.controller;

import com.atzhongruan.springboot_oss.common.JsonResult;
import com.atzhongruan.springboot_oss.utils.OssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


/**
 * <一句话功能简述>
 * <功能详细描述>
 *
 * @author Administrator
 * @version [版本号, 2019/12/13 0013]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@RestController
public class TestController {
    /**
     * @return
     * @function 视频上传
     */
    @PostMapping("/article/uploadVideo")
    public JsonResult uploadVideo(@RequestParam(value = "file", required = false) MultipartFile file) {
        if (file == null) {
            return new JsonResult("500", "内容为空");
        } else {
            return new JsonResult("200", OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_VIDEO));
        }

    }

    /**
     * @param file
     * @return
     * @function 图片上传
     */
    @PostMapping("/article/uploadImage")
    public JsonResult uploadImages(@RequestParam(value = "file", required = false) MultipartFile file) {
        if (file == null) {
            return new JsonResult("500", "内容为空");
        } else {
            return new JsonResult("200", OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_IMAGES));
        }
    }

//    /**
//     * 删除OSS对象
//     *
//     */
//    @Override
//    public boolean deleteArtImg(Integer artId) {
//        List<ArticleImages> images = imagesMapper.selectImagesList(artId);
//        List<String> strings = images
//                .stream()
//                .map(item -> item.getImgUrl())
//                .collect(Collectors.toList())
//                .stream()
//                .filter((item) -> item.length() > 0)
//                .collect(Collectors.toList());
//        if(strings.size() > 0){
//            imagesMapper.deleteImagesList(artId);
//            OssUtil.delete(strings);
//        }
//        return true;
//    }
}

五、结构图

参考文章:https://blog.csdn.net/yhflyl/article/details/86406641

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!