阿里对象存储对OSS文件上传的封装

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yhflyl/article/details/86168306

依赖

<!-- 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>

OSS工具类

package com.lehui.molong.util;


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

import org.apache.commons.io.FilenameUtils;

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


/**
 * @Author 进击的coder
 * 对象存储api封装
 */
public class OssUtil {

    /**
     * 域名
     */
    private final static String OSS_END_POINT = "xxxxx.xxxxxxx.com";

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

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

    /**
     * 存储空间
     */
    private final static String OSS_BUCKET_NAME = "xxxxxx";

    /**
     * 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);
            return fileDirType.getDir() + "/" + fileName;

        } catch (IOException e) {
            System.out.println("上传文件失败");
            throw new RuntimeException("上传文件失败");
        }
    }




    /**
     * 获取文件路径
     * @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;
    }

}

使用

/**
 * @function 视频上传
 * @return
 */
@PostMapping("/article/uploadVideo")
public JsonResult uploadVideo(@RequestParam(value = "file", required = false) MultipartFile file) {
    if(file == null){
        return new JsonResult(ResultCode.FAIL, "内容为空");
    }else{
        return new JsonResult(ResultCode.SUCCESS, OssUtil.upload(file, OssUtil.FileDirType.ARTICLE_VIDEO));
    }

}

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

参考:https://blog.csdn.net/zhanghan18333611647/article/details/79053613

猜你喜欢

转载自blog.csdn.net/yhflyl/article/details/86168306