目录
2-1、spring-boot的pom.xml中添加组件【这里使用的是3.20.6.1版】
2-2、spring-boot的application.yml文件中配置
前言
有些情况下,我们是需要存储到其他云服务器的【我们只需要购买服务即可】,比如项目中的一些图片或者文件,这里我们选用是华为云的OBS服务
1、购买服务并从官网获得我们项目所需的配置参数
1-1、登录华为云
对象存储服务OBS官网_海量安全高可靠_数据云存储解决方案-华为云
1-2、进入控制台
1-3、创建桶
1-4、获取sk、ak
2、spring-boot项目集成OBS服务器
2-1、spring-boot的pom.xml中添加组件【这里使用的是3.20.6.1版】
<dependency>
<groupId>com.huaweicloud</groupId>
<artifactId>esdk-obs-java</artifactId>
<version>3.20.6.1</version>
</dependency>
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;
/**
* @ClassName: HweiOBSConfig
* @Description: 华为云OBS配置类
* @Author: wuhuiju
* @Date: 2021-12-21 15:56
* @Version: 1.0
*/
@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;
/**
* @Description 获取OBS客户端实例
* @author wuhuiju
* @date 2021/12/21 15:57
* @return
* @return: com.obs.services.ObsClient
*/
public ObsClient getInstance() {
return new ObsClient(accessKey, securityKey, endPoint);
}
/**
* @Description 销毁OBS客户端实例
* @author wuhuiju
* @date 2021/12/21 17:32
* @param: obsClient
* @return
*/
public void destroy(ObsClient obsClient){
try {
obsClient.close();
} catch (ObsException e) {
log.error("obs执行失败", e);
} catch (Exception e) {
log.error("执行失败", e);
}
}
/**
* @Description 微服务文件存放路径
* @author wuhuiju
* @date 2021/12/21 15:57
* @return
* @return: java.lang.String
*/
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;
/**
* @Description 华为云OBS服务接口
* @author wuhuiju
* @date 2021/12/21 17:01
*/
public interface HweiYunOBSService {
/**
* @Description 删除文件
* @author wuhuiju
* @date 2021/12/21 17:02
* @param: objectKey 文件名
* @return: boolean 执行结果
*/
boolean delete(String objectKey);
/**
* @Description 批量删除文件
* @author wuhuiju
* @date 2021/12/21 17:02
* @param: objectKeys 文件名集合
* @return: boolean 执行结果
*/
boolean delete(List<String> objectKeys);
/**
* @Description 上传文件
* @author wuhuiju
* @date 2021/12/21 17:03
* @param: uploadFile 上传文件
* @param: objectKey 文件名称
* @return: java.lang.String url访问路径
*/
String fileUpload(MultipartFile uploadFile, String objectKey);
/**
* @Description 文件下载
* @author wuhuiju
* @date 2021/12/21 17:04
* @param: objectKey
* @return: java.io.InputStream
*/
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;
/**
* @ClassName: HweiYunOBSServiceImpl
* @Description: 华为云OBS服务业务层
* @Author: wuhuiju
* @Date: 2021-12-21 17:05
* @Version: 1.0
*/
@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<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、 添加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;
/**
* @ClassName: ObsController
* @Description: OBS服务器Controller
* @Author: wuhuiju
* @Date: 2021-12-21 15:20
* @Version: 1.0
*/
@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<String> 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