SpringBoot整合华为云OBS文件存储服务器

一、前言

对象存储服务(Object Storage Service,OBS)是一个基于对象的海量存储服务,为客户提供海量、安全、高可靠、低成本的数据存储能力。OBS系统和单个桶都没有总数据容量和对象/文件数量的限制,为用户提供了超大存储容量的能力,适合存放任意类型的文件,适合普通用户、网站、企业和开发者使用。OBS是一项面向Internet访问的服务,提供了基于HTTP/HTTPS协议的Web服务接口,用户可以随时随地连接到Internet,通过OBS管理控制台或各种OBS工具访问和管理存储在OBS中的数据。此外,OBS支持SDK和OBS API接口,可使用户方便管理自己存储在OBS上的数据,以及开发多种类型的上层业务应用。

二、快速开始

2.1、pom.xml依赖引入

 <!--华为云文件存储-->
        <dependency>
            <groupId>com.huaweicloud</groupId>
            <artifactId>esdk-obs-java</artifactId>
            <version>3.20.6.1</version>
        </dependency>

2.2、config配置类

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author wno5974
 * @create 2023-06-09 22:17
 * @Deprecated
 */
@Data
@Slf4j
@Configuration
public class HweiOBSConfig {
    /**
     * 访问密钥AK
     */
    @Value("${hwyun.obs.accessKey}")
    private String accessKey;

    /**
     * 访问密钥SK
     */
    @Value("${hwyun.obs.securityKey}")
    private String securityKey;

    /**
     * 终端节点
     */
    @Value("${hwyun.obs.endPoint}")
    private String endPoint;

    /**
     * 桶
     */
    @Value("${hwyun.obs.bucketName}")
    private String bucketName;

 
    public ObsClient getInstance() {
        return new ObsClient(accessKey, securityKey, endPoint);
    }


    public void destroy(ObsClient obsClient){
        try {
            obsClient.close();
        } catch (ObsException e) {
            log.error("obs执行失败", e);
        } catch (Exception e) {
            log.error("执行失败", e);
        }
    }


    public static String getObjectKey() {
        // 项目或者服务名称 + 日期存储方式
        return "OBS" + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date() )+ "/";
    }
}

2.3、OBSService调用

/**
 * @author wno5974
 * @create 2023-06-12 13:48
 * @Deprecated
 */
public interface OBSService {

    boolean delete(String objectKey);

    boolean delete(List<String> objectKeys);


    String fileUpload(MultipartFile uploadFile, String objectKey);


    InputStream fileDownload(String objectKey);
}

2.3、OBSServiceImpl调用

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.internal.ObsService;
import com.obs.services.model.*;
import com.won.pure.config.HweiOBSConfig;
import com.won.pure.file.service.OBSService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @author wno5974
 * @create 2023-06-09 22:20
 * @Deprecated
 */

@Slf4j
@Service
public class ObsServiceImpl implements OBSService {

    @Autowired
    private HweiOBSConfig hweiOBSConfig;

    @Override
    public boolean delete(String objectKey) {
        ObsClient obsClient = null;
        try {
            // 创建ObsClient实例
            obsClient = hweiOBSConfig.getInstance();
            // obs删除
            obsClient.deleteObject(hweiOBSConfig.getBucketName(), objectKey);
        } catch (ObsException e) {
            log.error("obs删除保存失败", e);
        } finally {
            hweiOBSConfig.destroy(obsClient);
        }
        return true;
    }

    @Override
    public boolean delete(List<String> objectKeys) {
        ObsClient obsClient = null;
        try {
            obsClient = hweiOBSConfig.getInstance();
            DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(hweiOBSConfig.getBucketName());
            objectKeys.forEach(x -> deleteObjectsRequest.addKeyAndVersion(x));
            // 批量删除请求
            obsClient.deleteObjects(deleteObjectsRequest);
            return true;
        } catch (ObsException e) {
            log.error("obs删除保存失败", e);
        } finally {
            hweiOBSConfig.destroy(obsClient);
        }
        return false;
    }

    @Override
    public String fileUpload(MultipartFile uploadFile, String objectKey) {
        ObsClient obsClient = null;
        try {
            String bucketName = hweiOBSConfig.getBucketName();
            obsClient = hweiOBSConfig.getInstance();
            // 判断桶是否存在
            boolean exists = obsClient.headBucket(bucketName);
            if (!exists) {
                // 若不存在,则创建桶
                HeaderResponse response = obsClient.createBucket(bucketName);
                log.info("创建桶成功" + response.getRequestId());
            }
            InputStream inputStream = uploadFile.getInputStream();
            long available = inputStream.available();
            PutObjectRequest request = new PutObjectRequest(bucketName, objectKey, inputStream);

            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(available);
            request.setMetadata(objectMetadata);
            // 设置对象访问权限为公共读
            request.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
            PutObjectResult result = obsClient.putObject(request);

            // 读取该已上传对象的URL
            log.info("已上传对象的URL" + result.getObjectUrl());
            return result.getObjectUrl();
        } catch (ObsException e) {
            log.error("obs上传失败", e);
        } catch (IOException e) {
            log.error("上传失败", e);
        } finally {
            hweiOBSConfig.destroy(obsClient);
        }
        return null;
    }

    @Override
    public InputStream fileDownload(String objectKey) {
        ObsClient obsClient = null;
        try {
            String bucketName = hweiOBSConfig.getBucketName();
            obsClient = hweiOBSConfig.getInstance();
            ObsObject obsObject = obsClient.getObject(bucketName, objectKey);
            return obsObject.getObjectContent();
        } catch (ObsException e) {
            log.error("obs文件下载失败", e);
        } finally {
            hweiOBSConfig.destroy(obsClient);
        }
        return null;
    }
}

2.4、OBS控制层

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.obs.services.exception.ObsException;
import com.won.pure.file.service.OBSService;
import com.won.pure.utils.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @author wno5974
 * @create 2023-06-09 22:23
 * @Deprecated
 */
@Api(tags = "华为云接口列表")
@RestController
@RequestMapping({"file"})// @RequestMapping("/file")
public class ObsController {

    @Autowired
    private OBSService hweiYunOBSService;

    @RequestMapping(value = "upload")
    public Result save(@RequestParam("file") MultipartFile file) throws IOException {
        /*if (FileUtil.isEmpty(file.getResource().getFile())) {
            return Result.fail("文件为空");
        }*/
         String test = hweiYunOBSService.fileUpload(file, file.getOriginalFilename());
        return Result.ok("执行成功:"+test);
    }

    @RequestMapping(value = "delete/{fileName}", method = RequestMethod.POST)
    public Result delete(@PathVariable String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return Result.fail("删除文件为空");
        }
        final boolean delete = hweiYunOBSService.delete(fileName);
        return Result.fail(delete);
    }

    @RequestMapping(value = "deletes", method = RequestMethod.POST)
    //@RequestParam 获取List,数组则不需要
    public Result delete(@RequestParam("fileNames") List<String> fileNames) {
        if (ArrayUtil.isEmpty(fileNames)) {
            return Result.fail("删除文件为空");
        }
        final boolean delete = hweiYunOBSService.delete(fileNames);
        return Result.fail(delete);
    }


    @RequestMapping(value = "download/{fileName}", method = RequestMethod.POST)
    public Result download(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return Result.fail("下载文件为空");
        }
        try (InputStream inputStream = hweiYunOBSService.fileDownload(fileName); BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream())) {
            if (inputStream == null) {
                return Result.fail("文件不存在");
            }
            // 为防止 文件名出现乱码
            final String userAgent = request.getHeader("USER-AGENT");
            // IE浏览器
            if (StrUtil.contains(userAgent, "MSIE")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                // google,火狐浏览器
                if (StrUtil.contains(userAgent, "Mozilla")) {
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                } else {
                    // 其他浏览器
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                }
            }
            response.setContentType("application/x-download");
            // 设置让浏览器弹出下载提示框,而不是直接在浏览器中打开
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            IoUtil.copy(inputStream, outputStream);
            return null;
        } catch (IOException | ObsException e) {
            return Result.fail(e);
        }
    }
}

posted on 2026-08-10 15:34  爱河  阅读(2)  评论(0)    收藏  举报

导航