栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring-boot项目整合obs服务器-华为云

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring-boot项目整合obs服务器-华为云

目录

 前言

1、购买服务并从官网获得我们项目所需的配置参数

1-1、登录华为云

1-2、进入控制台

1-3、创建桶 ​

​1-4、获取sk、ak

2、spring-boot项目集成OBS服务器

2-1、spring-boot的pom.xml中添加组件【这里使用的是3.20.6.1版】

2-2、spring-boot的application.yml文件中配置

2-3、 添加业务层【方法内有用到hutool的工具包】

2-4、 添加Controller层

 3、验证接口实现(这里使用postMan工具,其他也可)

3-1、上传接口:测试文件名称(test.jpg)

3-2、下载文件

3-3、删除文件(批量删除同理)

3-4、批量删除

借鉴 


 

 前言

        有些情况下,我们是需要存储到其他云服务器的【我们只需要购买服务即可】,比如项目中的一些图片或者文件,这里我们选用是华为云的OBS服务

1、购买服务并从官网获得我们项目所需的配置参数

 1-1、登录华为云

https://www.huaweicloud.com/product/obs.html

1-2、进入控制台

1-3、创建桶 

 

   1-4、获取sk、ak

2、spring-boot项目集成OBS服务器

        2-1、spring-boot的pom.xml中添加组件【这里使用的是3.20.6.1版】

	com.huaweicloud
	esdk-obs-java
	3.20.6.1

        2-2、spring-boot的application.yml文件中配置
hwyun: # 华为云OBS配置信息
  obs:
    accessKey: D*****N
    securityKey: h*******3
    endPoint: o********m
    bucketName: j**k

                创建对应的HweiOBSConfig类(参数)

package com.example.study.springboot.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;


@Data
@Slf4j
@Configuration
public class HweiOBSConfig {
    
    @Value("${hwyun.obs.accessKey}")
    private String accessKey;

    
    @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 "Hwei" + "/" + new SimpleDateFormat("yyyy-MM-dd").format(new Date() )+ "/";
    }
}

        2-3、 添加业务层【方法内有用到hutool的工具包】
package com.example.study.springboot.background.service;

import org.springframework.web.multipart.MultipartFile;

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


public interface HweiYunOBSService {

    
    boolean delete(String objectKey);

    
    boolean delete(List objectKeys);

    
    String fileUpload(MultipartFile uploadFile, String objectKey);

    
    InputStream fileDownload(String objectKey);
}

package com.example.study.springboot.background.service.impl;

import com.example.study.springboot.background.service.HweiYunOBSService;
import com.example.study.springboot.config.HweiOBSConfig;
import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;
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;


@Slf4j
@Service
public class HweiYunOBSServiceImpl implements HweiYunOBSService {

    @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 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、 添加Controller层
package com.example.study.springboot.background.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.example.study.springboot.background.service.HweiYunOBSService;
import com.example.study.springboot.common.api.ResponseVO;
import com.example.study.springboot.common.utils.FileUtil;
import com.obs.services.exception.ObsException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
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;


@RestController
@RequestMapping({ "file" })// @RequestMapping("/file")
public class HweiYunOBSController {

    @Resource
    private HweiYunOBSService hweiYunOBSService;

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public ResponseVO save(@RequestParam(value = "file", required = false) MultipartFile file) {
        if (FileUtil.isEmpty(file)) {
            return ResponseVO.error("文件为空");
        }
        final String test = hweiYunOBSService.fileUpload(file, file.getOriginalFilename());
        return ResponseVO.ok("执行成功",test);
    }

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

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


    @RequestMapping(value = "download/{fileName}", method = RequestMethod.POST)
    public ResponseVO download(HttpServletRequest request, HttpServletResponse response, @PathVariable String fileName) {
        if (StrUtil.isEmpty(fileName)) {
            return ResponseVO.error("下载文件为空");
        }
        try (InputStream inputStream = hweiYunOBSService.fileDownload(fileName);BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream())){
            if(inputStream == null) {
                return ResponseVO.error();
            }
            // 为防止 文件名出现乱码
            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 ResponseVO.error();
        }
    }
}

 3、验证接口实现(这里使用postMan工具,其他也可)

        3-1、上传接口:测试文件名称(test.jpg)

        上传后可以预览:

        3-2、下载文件

        3-3、删除文件(批量删除同理)

        3-4、批量删除

借鉴 

(1条消息) springboot整合obs-华为云-鲲鹏技术-OBS-对象储存技术(上传文件/图片)_小龙coding的博客-CSDN博客_springboot整合obs

(1条消息) 华为云OBS数据桶使用_豆芽菜-CSDN博客_华为云obs桶

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/677734.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号