0
点赞
收藏
分享

微信扫一扫

SpringBoot 集成华为云(对象存储)


SpringBoot 集成华为云

  • 对象存储服务OBS
  • 1. 登录华为云获取所需资料
  • 1. Access Key Id、Secret Access Key
  • 2. 桶名称、终端节点访问Endpoint、访问域名
  • 2. 导入依赖
  • 3. 创建工具类

对象存储服务OBS

1. 登录华为云获取所需资料

1. Access Key Id、Secret Access Key

点击新增访问密钥,再下载密钥,打开csv文件获取里面的ak和sk

SpringBoot 集成华为云(对象存储)_maven

2. 桶名称、终端节点访问Endpoint、访问域名

SpringBoot 集成华为云(对象存储)_文件路径_02

2. 导入依赖

<!-- https://mvnrepository.com/artifact/com.huaweicloud/esdk-obs-java -->
<dependency>
    <groupId>com.huaweicloud</groupId>
    <artifactId>esdk-obs-java</artifactId>
    <version>3.20.6.1</version>
</dependency>

3. 创建工具类

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.obs.services.ObsClient;
import com.obs.services.model.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Lenovo
 */
@Slf4j
@Component
public class HuaweiObs {

    //Access Key Id
    private String ak = "Access Key Id";

    //Secret Access Key
    private String sk = "Secret Access Key";

    //桶名称
    private String bucketName = "桶名称";

    // 终端节点访问Endpoint
    private String endpoint = "Endpoint";

    // 文件目录
    private String prifix = "/文件目录";

    // 访问域名 在域名后面或文件目录前加“/”
    private String path = "访问域名";

    /**
     * 文件上传
     *
     * @param file
     * @return
     * @throws IOException
     */
    public String upload(MultipartFile file) throws IOException {
        ObsClient obsClient = null;
        try {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int day = cal.get(Calendar.DATE);
            String fileName = IdUtil.simpleUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
            String objectName = prifix + "/" + year + "/" + month + "/" + day + "/" + fileName;
            obsClient = new ObsClient(ak, sk, endpoint);
            HeaderResponse response = obsClient.putObject(bucketName, objectName, file.getInputStream());
            log.info(JSONObject.toJSONString(response));
            // 可选:调用成功后,记录调用成功的HTTP状态码和服务端请求ID
            int statusCode = response.getStatusCode();
            if (200 == statusCode) {
                String objectUrl = path + objectName;
                return objectUrl;
            }
        } finally {
            obsClient.close();
        }
        return null;
    }

    /**
     * 上传文件--流式
     *
     * @param fileName 上传文件名称
     * @param is       文件流
     * @return
     */
    public String uploadFile(String fileName, InputStream is) throws IOException {
        ObsClient obsClient = null;
        try {
            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH);
            int day = cal.get(Calendar.DATE);
            String objectName = prifix + "/" + year + "/" + month + "/" + day + "/" + fileName;
            obsClient = new ObsClient(ak, sk, endpoint);
            HeaderResponse response = obsClient.putObject(bucketName, objectName, is);
            log.info(JSONObject.toJSONString(response));
            // 可选:调用成功后,记录调用成功的HTTP状态码和服务端请求ID
            int statusCode = response.getStatusCode();
            if (200 == statusCode) {
                String objectUrl = path + objectName;
                return objectUrl;
            }
        } finally {
            obsClient.close();
        }
        return null;
    }

    /**
     * 上传文件--字节数组
     *
     * @param fileName 上传文件名称
     * @param fileType 文件路径
     * @param is       文件流
     * @return
     */
    public boolean uploadFileByte(String fileName, FileType fileType, byte[] is) {
        ObsClient obsClient = null;
        try {
            String objectName = fileType.getType().concat("/").concat(fileName);
            obsClient = new ObsClient(ak, sk, endpoint);
            HeaderResponse response = obsClient.putObject(bucketName, objectName, new ByteArrayInputStream(is));
            // 可选:调用成功后,记录调用成功的HTTP状态码和服务端请求ID
            int statusCode = response.getStatusCode();
            if (200 == statusCode) {
                return true;
            }
            obsClient.close();
        } catch (IOException e) {
            log.info("文件上传失败:{}", e.getMessage(), e);
        }
        return false;
    }

    /**
     * 下载文件
     *
     * @param fileName 文件名称
     * @param fileType 文件路径
     * @return
     */
    public String getDownloadUrl(String fileName, FileType fileType) {
        ObsClient obsClient = null;
        obsClient = new ObsClient(ak, sk, endpoint);
        // URL有效期,3600秒.5分钟
        long expireSeconds = 3600L;
        String objectName = fileType.getType().concat("/").concat(fileName);
        TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.GET, expireSeconds);
        request.setBucketName(bucketName);
        request.setObjectKey(objectName);
        TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
        return response.getSignedUrl();
    }

    /**
     * 获取上传地址
     *
     * @param fileName 文件名称
     * @param fileType 文件路径
     * @return
     */
    public String getUploadUrl(String fileName, FileType fileType) {
        try {
            // 创建ObsClient实例
            ObsClient obsClient = new ObsClient(ak, sk, endpoint);
            // URL有效期,3600秒
            long expireSeconds = 3600L;
            Map<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/octet-stream");
            String objectName = fileType.getType().concat("/").concat(fileName);
            TemporarySignatureRequest request = new TemporarySignatureRequest(HttpMethodEnum.PUT, expireSeconds);
            request.setBucketName(bucketName);
            request.setObjectKey(objectName);
            request.setHeaders(headers);
            TemporarySignatureResponse response = obsClient.createTemporarySignature(request);
            return response.getSignedUrl();
        } catch (Exception e) {
            log.error("获取上传地址异常:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 下载文件返回字节数组
     *
     * @param fileName 文件名称
     * @param fileType 文件路径
     * @return
     */
    public byte[] downloadFile(String fileName, FileType fileType) {
        try {
            InputStream inputStream = downloadFileInputStream(fileName, fileType);
            byte[] bytes = IOUtils.toByteArray(inputStream);
            return bytes;
        } catch (Exception e) {
            log.error("下载文件异常:{}", e.getMessage(), e);
        }
        return null;
    }

    /**
     * 上传视频
     *
     * @param fileName 文件名称
     * @param fileType 文件路径
     * @return
     */
    public boolean uploadFileVideo(String fileName, FileType fileType, InputStream is) {
        try {
            String objectName = fileType.getType().concat("/").concat(fileName);
            ObsClient obsClient = new ObsClient(ak, sk, endpoint);
            // 添加 ContentType (添加后可在浏览器中直接浏览,而非下载链接)
            obsClient.putObject(bucketName, objectName, is);
            obsClient.close();
            return true;
        } catch (Exception e) {
            log.error("上传视频文件异常:{}", e.getMessage(), e);
        }
        return false;
    }

    /**
     * 下载文件返回流式
     *
     * @param fileName 文件名称
     * @param fileType 文件路径
     * @return
     */
    public InputStream downloadFileInputStream(String fileName, FileType fileType) {
        try {
            String objectName = fileType.getType().concat("/").concat(fileName);
            // 用户拿到STS临时凭证后,通过其中的安全令牌(SecurityToken)和临时访问密钥(AccessKeyId和AccessKeySecret)生成OSSClient。
            ObsClient obsClient = new ObsClient(ak, sk, endpoint);
            ObsObject obsObject = obsClient.getObject(bucketName, objectName);
            obsClient.close();
            return obsObject.getObjectContent();
        } catch (Exception e) {
            log.error("下载文件异常:{}", e.getMessage(), e);
        }
        return null;
    }


    public enum FileType {
        TEST("TEST", "测试");

        private String type;
        private String desc;

        FileType(String type, String desc) {
            this.type = type;
            this.desc = desc;
        }

        public String getType() {
            return type;
        }

        public String getDesc() {
            return desc;
        }
    }
}

到这里我们就可以开始我自己的上传操作了。


举报

相关推荐

0 条评论